I have this test.php where i have this info :
callername1 : 'Fernando Verdasco1'
callername2 : 'Fernando Verdasco2'
callername3 : 'Fernando Verdasco3'
callername4 : 'Fernando Verdasco4'
callername5 : 'Fernando Verdasco5'
this page automatically changes that name every 10 min
In this another page test1.php
I need a php code that takes only the name of the callername3 and echo'it
Fernando Verdasco3
I've tried this like so test1.php?id=callername3
<?php
$Text=file_get_contents("test.php");
if(isset($_GET["id"])){
$id = $_GET["id"];
parse_str($Text,$data);
echo $data[$id];
} else {
echo "";
}
?>
but no result.
Is there any other option?
If i have "=" instade of ":"
callername1 = 'Fernando Verdasco1'
callername2 = 'Fernando Verdasco2'
callername3 = 'Fernando Verdasco3'
callername4 = 'Fernando Verdasco4'
callername5 = 'Fernando Verdasco5'
And i use This php Code it works
<?php
$Text=file_get_contents("test.php")
;preg_match_all('/callername3=\'([^\']+)\'/',$Text,$Match);
$fid=$Match[1][0];
echo $fid;
?>
i need this to work with ":"
Help?
You should store data in a file with the .php extension, since it's not executable PHP. I looks like you're going for the JSON syntax.
Since you need it to work with ':' I assume, for whatever reason, you can't change the format. Your example with '=' works because of the regexp:
preg_match_all('/callername3=\'([^\']+)\'/',$Text,$Match);
This says, match text like callername3= followed by a ' followed by one or more chars that are not a ' followed by a final '. Everything between the 's is stored in $Match[1][0] (if there were more parts in brackets they be stored in $Match[2][0], etc).
Your example doesn't work since it doesn't account for the spaces before and after the = sign. But we can fix that up and change it to work for : like this:
preg_match('/callername3\s*:\s*\'([^\']+)\'/',$Text,$Match);
echo $Match[1] ."\n";
This displays:
Fernando Verdasco3
And what that regular expression is match text that start callername3 followed by any amount of whitespace (that's the \s*) followed by a :, followed by any amount of whitespace, followed by a name in quotes (that is stored in $Match[1], this is the area of the regular expression enclosed in parenthesis).
I've also used just preg_match because it looks like you only need to match one example.
There is a rather simple approach to tihs:
$fData = file_get_contents("test.php");
$lines = explode("\n", $fData);
foreach($lines as $line) {
$t = explode(":", $line);
echo trim($t[1]); // This will give you the name
}
Related
I am using the a db field merchant_sku_item in a form. the original value is separated by / in the db like this:
2*CC689/1*CC368-8/1*SW6228-AB
I want to display in a text area on each line so I tried like this:
<textarea name="merchant_sku_item" rows="5" class="form-control" id="merchant_sku_item"><?
$items=explode('/',$merchant_sku_item);
foreach($items as $item){
echo $item."\r\n";
}
?></textarea>
All works fine:
2*CC689
1*CC368-8
1*SW6228-AB
but when I post the form I get a value like this:
2*CC689 1*CC368-8 1*SW6228-AB
but I wan't it back in the original format to update the DB in the correct format:
2*CC689/1*CC368-8/1*SW6228-AB
I tried to implode it with the / but I think it's just one string now so it's not working. I could replace the spaces I guess but this will not work if the field contains spaces.
Could somebody please tell me the best way to handle this?
The explode is correct, but you cannot just echo $item . "\r\n" because if $item contains </textarea> or whatever HTML you'll skrew up the page. You have to use echo htmlspecialchars($item) . "\n";. Normally, HTML pages have Linux line endings with "\n" and not Windows line endings with "\r\n".
To re-create the value for the DB, you have to take in consideration that the user may add some spaces or new lines. So you might not just get "\r\n" between the values but also " \n" or I don't know what. This is why a regular expression will be more flexible than a simple explode().
The regular expression pattern: \s+
The pattern \s will match any space, tab or new line chars. If you add the + sign after, it means that it can be 1 or multiple times. So this means that " \r\n" will match as it contains spaces, a carriege return and a new line. In PHP, you put the pattern between a delimiter char that you choose and that you put at the begin and the end. Commonly it's a slash so it becomes /\s+/. But you sometimes see also #\s+# or ~\s+~. After this delimiter, you can put some flags to change the way the regular expression is executed. Typically /hello/i will match "Hello" or "hello" because the i flag makes the search case-insensitive.
Similar to what you did: explode and re-implode example:
<?php
// Example of values that could be posted because users are always
// stupid and add spaces that they then don't see anymore.
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
];
foreach ($examples as $merchant_sku_item) {
$values = preg_split('/\s+/', $merchant_sku_item);
$merchant_sku_item_for_db = implode('/', $values);
echo $merchant_sku_item_for_db . "\n";
}
?>
Output:
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
2*CC689/1*CC368-8/1*SW6228-AB
Simplier, you could also just do a replacement with the same regular expression like this:
<?php
// Example of values that could be posted.
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
];
foreach ($examples as $merchant_sku_item) {
$merchant_sku_item_for_db = preg_replace('/\s+/', '/', $merchant_sku_item);
echo $merchant_sku_item_for_db . "\n";
}
?>
And just another important point regarding the data the user could input: What happens if the user types "2*CC/689" in the textarea?
Well, this will break your DB value :-/
This means that you have to validate the user input with some checks:
<?php
header('Content-Type: text/plain');
$examples = [
"2*CC689 1*CC368-8 1*SW6228-AB", // spaces
"2*CC689\n1*CC368-8\n1*SW6228-AB", // new lines
"2*CC689\r\n1*CC368-8\r\n1*SW6228-AB", // carriege returns and new lines
"2*CC689\n 1*CC368-8 \n1*SW6228-AB", // new lines and spaces
// Test with invalid datas:
"2*C/C689\n1*CC368-8\n1*SW6228-AB", // slash not allowed
"*CC689\n1*CC368-8\n1*SW6228-AB", // missing number before the *
"1*\n1*CC368-8\n1*SW62?28-AB", // missing product identifier and invalid ?
"1CC689 1*CC368-8 1SW6228-AB", // missing *
];
foreach ($examples as $example_nbr => $merchant_sku_item) {
echo str_repeat('=', 80) . "\n";
echo "Example $example_nbr\n\$merchant_sku_item = \"$merchant_sku_item\"\n";
$values = preg_split('/\s+/', $merchant_sku_item);
$errors = [];
foreach ($values as $i => $value) {
echo "Value $i = \"$value\"";
// Pattern: a number followed by * and followed by a product id (length between 3 and 10).
if (!preg_match('/^\d+\*[\d\w-]{3,10}$/i', $value)) {
echo " <-- ERROR\n";
$errors[] = $value;
} else {
echo "\n"; // It's ok
}
}
if (!empty($errors)) {
// You should handle the error and reload the form with the posted value and an error
// message explaining to the user what format is allowed.
echo "ERROR: Cannot save the value because the following products are wrong:\n";
echo implode("\n", $errors) . "\n";
}
}
?>
Test it here: https://onecompiler.com/php/3xtff6nk8
You can use preg_replace for your final post string like below code
$str = "2*CC689 blue 1*CC368-8 red 1*SW6228-AB";
$items = preg_replace('/\s+/', '/', $str);
echo $items;
output
2*CC689/blue/1*CC368-8/red/1*SW6228-AB
I Hope understand your question exactly.
Try replacing the created spaces and removing newline characters like so:
<?php
$merchant_sku_item = str_replace("\r\n","/",trim($_POST["merchant_sku_item"]));
?>
Make it this way:
<textarea name="merchant_sku_item" rows="5" class="form-control" id="merchant_sku_item"><?
$items=explode('//',$merchant_sku_item);
foreach($items as $item){
echo $item."\r\n";
}
?></textarea>
I have a an url which looks like this https://URL.DOMAIN/blog.php?id=43&q=echo%20%27test%27.
When I use <?php echo $_GET['q'] ?> it displays echo 'test' which is what I want.
I am using this variable inside a preg_replace function which is basically made to apply a yellow background under matched strings:
preg_replace('/\b('.$_GET['q'].')\b/iu', '<span class="research-news-found">$1</span>', $news_content);
It works perfectly for "normal" strings like "apple" or whatever, but when there is a ' inside the search query it doesn't match anything.
Code example
$news_content = $news_display['news_description'];
if(isset($_GET['q'])){
$news_content = preg_replace('/\b('.$_GET['q'].')\b/iu', '<span class="research-news-found">$1</span>', $news_content);
}
$news_display['news_description'] contains the text output from DB.
Just make the pattern greedy ? and remove the trailing word boundary \b since ' is not a word character and is a word boundary:
$news_content = preg_replace('/\b('.$_GET['q'].'?)/iu',
'<span class="research-news-found">$1</span>',
$news_content);
Demo
But if you are hoping that it will actually echo test, then no. You would need to restructure your question to state what you want to achieve, not how to get this replacement to work.
This is my code for test.php
<?PHP
include("connect.php");
$search_value = mysqli_real_escape_string($db_mysqli,$_GET['search_value']);
$search_value_show_text = preg_replace('/\+/', ' ', $search_value);
echo $search_value_show_text;
?>
When i test www.example.com/test?search_value=%2B+%2B
It's not echo anything (i mean it's show 3 spaces).
I want to show + +
How can i do ?
You seem not understand what you are doing. Plus sign in url means space, so that's one. Then you replace two other pluses (which are automatically decoded from %2B form) with spaces and you end up with three spaces total. Simply do nothing (or use urldecode() if needed) with your inpit data and you should be good.
Also you use mysql related ed calls w/o using mysql - thats wrong
$search_value = 'www.example.com/test?search_value=%2B+%2B';
$search_value_show_text = preg_replace('/\+/', ' ', $search_value);
echo $search_value_show_text ."<br/>";
$search_value_show_text = preg_replace('/\%2B/', '+', $search_value_show_text);
echo $search_value_show_text;
output:
www.example.com/test?search_value=%2B %2B
www.example.com/test?search_value=+ +
I have a large number of ASCII text files and am listing out the contents of each using the code below:
<?php
$file = $_GET['file'];
$orig = file_get_contents($file);
$a =htmlentities($orig);
echo $a;
?>
Some strings of text in each ASCII file are references to file names of other files and I'm trying to find and replace them with a Hyperlink to that file.
For example, a text file might be called "LAB_E143.txt" which looks like this:
LAB_E143:
LDX $#FF ; load X with $FF
JSR LAB_E151 ; jump to this location
and what I'm trying to find & replace are references beginning with "LAB_" (e.g. LAB_E151 in the example above) so that it displays the text as a Hyperlink with a href of:
http:\\capture.php?file=lab_e151.txt
Clicking on that link will then display the contents of that particular text file and so on. All the references begin with "LAB_" followed by 4 variable characters.
I've tried str_replace but am struggling to parse the 4 variable characters each time.
Any help / pointers greatly appreciated
You should use Regex for such cases. As shudder mentioned, preg_replace_callback should be the best function to use for this purpose.
Detect all references with the following Regex: /LAB_(?<id>\S{4})/
Write a function to replace the matches with the <a> tag
That's it.
$text = 'LAB_8435 Lorem ipsum dolor sit amet. LAB_8337 Amet.';
$formattedText = preg_replace_callback('/LAB_(?<id>\S{4})/', function ($matches) {
return ''.$matches[0].'';
}, $text);
echo $formattedText;
Warning: you want to display file from specific folder - make sure that user can't change the path with provided string (file whitelist, filename sanitization), because it would be possible to do some serious damage.
I suggest not giving a clue that link is directly connected with included file name. Instead /capture.php?file=lab_e151.txt you may have /capture.php?id=e151 and then something like this:
$id = isset($_GET['id']) ? $_GET['id'] : ''; //in php7: $id = $_GET['id'] ?? '';
if (!preg_match('/[0-9A-Za-z]{4}/', $id)) { die('Invalid link'); }
$file = 'lab_' . $id . '.txt';
//...
$convertToLink = function ($matches) {
return '' . $matches[0] . '';
};
$code = preg_replace_callback('/LAB_([0-9A-Za-z]{4})/', $convertToLink, $string);
echo '<pre>' . $code . '</pre>';
If those 4 chars are hex number then you may use this pattern instead: /LAB_([0-9A-Fa-f]{4})/
I have huge online php fileset that is made dynamically.
It has links, even some invalid ones with quotes (made with frontpage)
index2.php?page=xd
index2.php?page=xj asdfa
index2.php?page=xj%20aas
index2.php?page=xj#jumpword
index2.php?page=gj#jumpword with spaces that arenot%20
index2.php?page=afdsdj#jumpword%20with
index2.php?page=xj#jumpword with "quotes" iknow
$input_lines=preg_replace("/(index2.php?page\=.*)(#[a-zA-Z0-9_ \\"]*)(\"\>)/U", "$0 --> $2", $input_lines);
I want all of those to be just with the # -part and not have the index2.php?page=* part.
I could not get this to work in whole evening. So please help.
In some cases, you can use parse_url to get attributes from the URL (ex: what is after the #), like so:
$urls = array(
'index2.php?page=xd',
'index2.php?page=xj asdfa',
'index2.php?page=xj%20aas',
'index2.php?page=xj#jumpword',
'index2.php?page=gj#jumpword with spaces that arenot%20',
'index2.php?page=afdsdj#jumpword%20with',
'index2.php?page=xj#jumpword with "quotes" iknow',
);
foreach($urls as $url){
echo 'For "' . $url . '": ';
$parsed = parse_url($url);
echo isset($parsed['fragment']) ? $parsed['fragment'] : 'DID NOT WORK';
echo '<br>';
}
Output:
For "index2.php?page=xd": DID NOT WORK
For "index2.php?page=xj asdfa": DID NOT WORK
For "index2.php?page=xj%20aas": DID NOT WORK
For "index2.php?page=xj#jumpword": jumpword
For "index2.php?page=gj#jumpword with spaces that arenot%20": jumpword with spaces that arenot%20
For "index2.php?page=afdsdj#jumpword%20with": jumpword%20with
For "index2.php?page=xj#jumpword with "quotes" iknow": jumpword with "quotes" iknow