php: string is double-quoted, not single-quoted. How to fix? - php

I was asking this SO question php: split string into 3 parts... and got excellent answers. However, I faced an issue. The issue is double-quoted string to process. Because of that it doesn't work as expected in one case when $sign is within the string.
$str = $_POST['source'];//comes double-quoted, example: "$abc$";
That way the code from the answer from the question mentioned above is:
<?php
$str = "$abc$$$";//comes from _POST['source'];
preg_match('/^([^\w]*)(\w+.*\w+)?([^\w]*)$/iu', $str, $matches);
$parts = array_slice($matches, 1);
print_r($parts);
?>
doesn't work and causes E_NOTICE : type 8 -- Undefined variable:
From what I've found the problem is "$abc$$$" is double quoted, not single quoted. That causes $ treating as a variable: SO: Dollar ($) sign in password string treated as variable
I've tried
$str = $_POST['source'];
$str = (string)$str;// I hoped to convert "$abc$$$" to '$abc$$$' (to make single-quoted)
but that doesn't help.
Any ideas how to face with this issue?

It works just fine. Its your testing that is causing the issue.
Do this instead
$_POST['source'] = '$abc$$$';
$str = $_POST['source'];
preg_match('/^([^\w]*)(\w+.*\w+)?([^\w]*)$/iu', $str, $matches);
$parts = array_slice($matches, 1);
print_r($parts);
Result
Array
(
[0] => $
[1] => abc
[2] => $$$
)
Additional Example
Look at this simple test. I load a variable using a single quoted string and var_dump shows it to me as a double quoted string.
$test = '$var';
var_dump($test);
Result
string(4) "$var"
Its just how the dump functions decide to show a string, the string has not been changed
Its only if within PHP itself you use a $ when creating a string variable using a double quoted string literal that this variable expansion takes place. This is something PHP does and nothing intrinsic about double quoted literals.
So this
$test = "$var";
Will generate an error if $var does not exists, or expand it if it does. But only because it being done in PHP code.

Related

PHP convert double quoted string to single quoted string

I know this question asked here many times.But That solutions are not useful for me. I am facing this problem very badly today.
// Case 1
$str = 'Test \300'; // Single Quoted String
echo json_encode(utf8_encode($str)) // output: Test \\300
// Case 2
$str = "Test \300"; // Double Quoted String
echo json_encode(utf8_encode($str)) // output: Test \u00c0
I want case 2's output and I have single quoted $str variable. This variable is filled from XML string parsing . And that XML string is saved in txt file.
(Here \300 is encoding of À (latin Charactor) character and I can't control it.)
Please Don't give me solution for above static string
Thanks in advance
This'll do:
$string = '\300';
$string = preg_replace_callback('/\\\\\d{1,3}/', function (array $match) {
return pack('C', octdec($match[0]));
}, $string);
It matches any sequence of a backslash followed by up to three numbers and converts that number from an octal number to a binary string. Which has the same result as what "\300" does.
Note that this will not work exactly the same for escaped escapes; i.e. "\\300" will result in a literal \300 while the above code will convert it.
If you want all the possible rules of double quoted strings followed without reimplementing them by hand, your best bet is to simply eval("return \"$string\""), but that has a number of caveats too.
May You are looking for this
$str = 'Test \300'; // Single Quoted String
echo json_encode(stripslashes($str)); // output: Test \\300

Convert a GET variable containing numbers range to string in PHP

I have a get variable in this format : 0-1499. Now I need to convert it to a string so that I can explode the variable. For this I tried to convert it to string , but I am not getting any output. Here is the sample code :
$mystring = $_GET['myvars']; //equals to 0-1499;
//$mystring = (string)$mystring;
$mystring = strval($mystring);
$mystring = explode("-",$mystring);
print_r($mystring);
The above print_r() shows an array Array ( [0] => [1] => 1499 ). That means it calculates the $mystring before converted into string. How can I send 0-1499 as whole string to explode ?
I have a get variable in this format : 0-1499
When you grab this variable from the URL say.. http://someurl.com/id=0-1499
$var = $_GET['id'];
This will be eventually converted to a string and you don't need to worry about it.
Illustration
FYI : The above illustration used the code which you provided in the question. I didn't code anything extra.
You need quotes, sir.
Should work fine like this.
$mystring = "0-1499";
$mystring = explode("-",$mystring);
print_r($mystring);
Without the quotes it was numbers / math.
0 minus 1499 = negative 1499
As you correctly note it treats the value as arithmetic and ignores the 0- part. If you know that the value you'll get is 0-n for some n, all you need to do is this:
$mystring="0-".$n;
$mystring=explode("0-", $mystring);
but explode here is a bit redundant. So,
$myarr=array();
$myarr[1]=strval($mystring);
$myarr[0]="0";
There you go.
Explode is used for strings.http://php.net/explode
<?php
$mystring = "0-1499";
$a=explode("-",$mystring);
echo $a[0];
echo "<br>";
echo $a[1];
?>
see it working here http://3v4l.org/DEstD

preg_replace and an array not working

This doesn't work. I expect it to replace each coinsurance of the array values with ralph. Instead, I get the unchanged value of $data back. Any insight as to why?
$data="there is a dog in the car out back";
$bill= explode(' ',$data);
$bob[0]="dog";
$bob[1]="car";
$bob[2]="back";
$qq = preg_replace("|($bob)|Ui", "ralph" , htmlspecialchars($data));
echo $qq;
If you interpolate an array like $bob in string context "$bob" then it just becomes "Array".
At the very least you would need to implode it again as alternatives list:
$regex_bob = implode("|", $bob); // you should also apply preg_quote()
# $regex_bob = "dog|car|back|...";
And then use a more sensible regex delimiter (as | is used for the alternatives):
$qq = preg_replace("~($regex_bob)~Ui", "ralph" , htmlspecialchars($data));
Just try this:
echo "|($bob)|Ui";
...and you will see what the problem is. If you just place an array into a string, it results in the string Array being added to the string - so the actual regex you are executing is:
"|(Array)|Ui"
You need to explicitly tell PHP how to convert the array to a string - in this case, I suggest you use implode():
$expr = "/(".implode('|',$bob).")/Ui";
$qq = preg_replace($expr, "ralph" , htmlspecialchars($data));
// Should return "there is a ralph in the ralph out ralph"
Note that I have also changed the delimiter to / - this is because you need to use | literally in the regex, so it is best to pick another delimiter.
Use it this way:
$data="there is a dog in the car out back";
$bill= explode(' ',$data);
$bob[0]="/dog/ui";
$bob[1]="/car/ui";
$bob[2]="/back/ui";
echo preg_replace($bob, "ralph", $data);
You have to pass a list of regular expressions, which you want to replace with a string or a list of replacements. More information: http://php.net/manual/en/function.preg-replace.php

Using preg_replace to back reference array key and replace with a value

I have a string like this:
http://mysite.com/script.php?fruit=apple
And I have an associative array like this:
$fruitArray["apple"] = "green";
$fruitArray ["banana"] = "yellow";
I am trying to use preg_replace on the string, using the key in the array to back reference apple and replace it with green, like this:
$string = preg_replace('|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|', 'http://mysite.com/'.$fruitArray[$1].'/', $string);
The process should return
http://mysite.com/green/
Obviously this isn’t working for me; how can I manipulate $fruitArray[$1] in the preg_replace statement so that the PHP is recognised, back referenced, and replaced with green?
Thanks!
You need to use the /e eval flag, or if you can spare a few lines preg_replace_callback.
$string = preg_replace(
'|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e',
' "http://mysite.com/" . $fruitArray["$1"] ',
$string
);
Notice how the whole URL concatenation expression is enclosed in single quotes. It will be interpreted as PHP expression later, the spaces will vanish and the static URL string will be concatenated with whatever is in the fruitArray.

PHP regex issue: cannot find $C

I'm trying to parse dollar amounts from a text of in mixed French (Canadian) and English. The text is in UTF-8. They use $C to denote currency. For some reason when I use preg_match neither the '$' nor the 'C' can be found. Everything else works fine. Any ideas?
e.g. use
preg_match_all('/\$C/u', $match)
on "Thanks for a payment of 46,00 $C" returns empty.
I think the regex can't find those characters because they aren't there. If you initialize the string like this:
$source = "Thanks for a payment of 46,00 $C";
...(i.e., as a double-quoted string literal), $C gets interpreted as a variable name. Since you never initialized that variable, it gets replaced with nothing in the actual string. You should either use single-quotes to initialize the string, or escape the dollar sign with a backslash like you did in the regex.
By the way, this couldn't be an encoding problem, because (in the example, at least), all the characters are from the ASCII character set. Whether it was encoded as UTF-8, ISO-8859-1 or ASCII, the binary representation of the string would be identical.
preg_match_all('/\$C/u', 'Thanks for a payment of 46,00 $C', $matches);
print_r($matches);
works fine for me:
Array
(
[0] => Array
(
[0] => $C
)
)
Maybe this helps:
// assuming $text is the input string
$matches = array();
preg_match_all('/([0-9,\\.]+)\\s*\\$C/u', $text, $matches);
if ($matches) {
$price = floatval(str_replace(',', '.', $matches[1][0]));
printf("%.2f\n", $price);
} else {
printf("No price found\n");
}
Just make sure the input string ($text) has been properly decoded into an Unicode string. (For example, if it's in UTF-8, use the utf8_decode function.)

Categories