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
Related
I have a problem with rtrim() function in php. I have string like this one:
$str = "<a id="AccountDocument_11" href="/view/id/11">Picture of Collateral</a> [2017-04-01],";
Like this, embed the string in array.
I want to remove that last comma in this string. rtrim not working.
When i remove that html elements from that string, rtrim() works perfectly. anyone help?
you have to change your string like this, then it will work, it does not work because your string is inappropriate:
$str = "<a id='AccountDocument_11' href='/view/id/11'>Picture of
Collateral</a> [2017-04-01],";
echo rtrim($str,",");
output is:
Picture of Collateral [2017-04-01]
The only difference is that double quoted strings interpret embedded variables and a number of escape sequences, while single quoted strings do not. E.g.:
Reference: When should you use single or double quotes in PHP?
write your code below it works
you have write string ""(double quote) and under string you also used "" string instead of this you use ''(single quote);
<?php
$str = "<a id='AccountDocument_11' href='/view/id/11'>Picture of Collateral</a> [2017-04-01],";
echo rtrim($str,",");
i believe you quoted the string wrong.
try the below:
$str = rtrim('<a id="AccountDocument_11" href="/view/id/11">Picture of Collateral</a> [2017-04-01],',',');
echo $str;
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.
I'm looking to use unpack().
This works:
$srbytes = "\x80\x3e\x00\x00";
$array1 = unpack("v",$srbytes);
This does not:
$num1 = "80"
$srbytes = "\x".$num1."\x3e\x00\x00";
$array1 = unpack("v",$srbytes);
or
$srbytes = "\x"."80\x3e\x00\x00";
$array1 = unpack("v",$srbytes);
Printing this with echo shows ASCII chars with the first full string but, the concatenated ones shows text until it passes where it was concatenated.
Comparing a full string against a concatenated ones shows false, even though they should be the same?
what is actually happening when I'm trying to concatenate
The character expansion won't work, because at the point that you do "\x" . "80" PHP already has two string literals. It can't be expected to figure that meant anything else but this.
Instead of trying to concatenate a hexadecimal value for expansion, just concatenate the actual character, by converting the hexadecimal value to a base10 integer, and passing it to chr(), which converts it to an actual byte.
$str = "";
$num1 = "80";
$str .= chr(base_convert($num1, 16, 10));
var_dump($str);
Gives you
string(1) "�"
When you actually look at the value of $srbytes in your example where you define it as a string literal "\x80\x3e\x00\x00", what you get is var_dump("\x80\x3e\x00\x00") giving you string(4) "�>", because PHP double quoted strings offer additional character expansion such as expanding on escaped hexadecimal values into bytes. However, var_dump("\x"."80\x3e\x00\x00") just gives you string(7) "\x80>", which is because the value "\x" by itself is just a literal "\x" as a string. So they aren't the same values, no.
If you want the 'literal' string use single quotes. Your issue is with escaped character sequences inside double quotes being evaluated. Example:
$srbytes = '\x'.'80\x3e\x00\x00';
echo $srbytes;
// \x80\x3e\x00\x00
var_dump($srbytes);
// string(16) "\x80\x3e\x00\x00"
$srbytes = "\x"."80\x3e\x00\x00";
echo $srbytes;
// \x80>
var_dump($srbytes);
//string(7) "\x80>"
http://php.net/manual/en/language.types.string.php
I have strings like these:
"my value1" => my value1
"my Value2" => my Value2
myvalue3 => myvalue3
I need to get rid of " (double-quotes) in end and start, if these exist, but if there is this kind of character inside String then it should be left there. Example:
"my " value1" => my " value1
How can I do this in PHP - is there function for this or do I have to code it myself?
The literal answer would be
trim($string,'"'); // double quotes
trim($string,'\'"'); // any combination of ' and "
It will remove all leading and trailing quotes from a string.
If you need to remove strictly the first and the last quote in case they exist, then it could be a regular expression like this
preg_replace('~^"?(.*?)"?$~', '$1', $string); // double quotes
preg_replace('~^[\'"]?(.*?)[\'"]?$~', '$1', $string); // either ' or " whichever is found
If you need to remove only in case the leading and trailing quote are strictly paired, then use the function from Steve Chambers' answer
However, if your goal is to read a value from a CSV file, fgetcsv is the only correct option. It will take care of all the edge cases, stripping the value enclosures as well.
I had a similar need and wrote a function that will remove leading and trailing single or double quotes from a string:
/**
* Remove the first and last quote from a quoted string of text
*
* #param mixed $text
*/
function stripQuotes($text) {
return preg_replace('/^(\'(.*)\'|"(.*)")$/', '$2$3', $text);
}
This will produce the outputs listed below:
Input text Output text
--------------------------------
No quotes => No quotes
"Double quoted" => Double quoted
'Single quoted' => Single quoted
"One of each' => "One of each'
"Multi""quotes" => Multi""quotes
'"'"#";'"*&^*'' => "'"#";'"*&^*'
Regex demo (showing what is being matched/captured): https://regex101.com/r/3otW7H/1
trim will remove all instances of the char from the start and end if it matches the pattern you provide, so:
$myValue => '"Hi"""""';
$myValue=trim($myValue, '"');
Will become:
$myValue => 'Hi'.
Here's a way to only remove the first and last char if they match:
$output=stripslashes(trim($myValue));
// if the first char is a " then remove it
if(strpos($output,'"')===0)$output=substr($output,1,(strlen($output)-1));
// if the last char is a " then remove it
if(strripos($output,'"')===(strlen($output)-1))$output=substr($output,0,-1);
As much as this thread should have been killed long ago, I couldn't help but respond with what I would call the simplest answer of all. I noticed this thread re-emerging on the 17th so I don't feel quite as bad about this. :)
Using samples as provided by Steve Chambers;
echo preg_replace('/(^[\"\']|[\"\']$)/', '', $input);
Output below;
Input text Output text
--------------------------------
No quotes => No quotes
"Double quoted" => Double quoted
'Single quoted' => Single quoted
"One of each' => One of each
"Multi""quotes" => Multi""quotes
'"'"#";'"*&^*'' => "'"#";'"*&^*'
This only ever removes the first and last quote, it doesn't repeat to remove extra content and doesn't care about matching ends.
This is an old post, but just to cater for multibyte strings, there are at least two possible routes one can follow. I am assuming that the quote stripping is being done because the quote is being considered like a program / INI variable and thus is EITHER "something" or 'somethingelse' but NOT "mixed quotes'. Also, ANYTHING between the matched quotes is to be retained intact.
Route 1 - using a Regex
function sq_re($i) {
return preg_replace( '#^(\'|")(.*)\1$#isu', '$2', $i );
}
This uses \1 to match the same type quote that matched at the beginning. the u modifier, makes it UTF8 capable (okay, not fully multibyte supporting)
Route 2 - using mb_* functions
function sq($i) {
$f = mb_substr($i, 0, 1);
$l = mb_substr($i, -1);
if (($f == $l) && (($f == '"') || ($f == '\'')) ) $i = mb_substr($i, 1, mb_strlen( $i ) - 2);
return $i;
}
You need to use regular expressions, look at:-
http://php.net/manual/en/function.preg-replace.php
Or you could, in this instance, use substr to check if the first and then the last character of the string is a quote mark, if it is, truncate the string.
http://php.net/manual/en/function.substr.php
How about regex
//$singleQuotedString="'Hello this 'someword' and \"somewrod\" stas's SO";
//$singleQuotedString="Hello this 'someword' and \"somewrod\" stas's SO'";
$singleQuotedString="'Hello this 'someword' and \"somewrod\" stas's SO'";
$quotesFreeString=preg_replace('/^\'?(.*?(?=\'?$))\'?$/','$1' ,$singleQuotedString);
Output
Hello this 'someword' and "somewrod" stas's SO
If you like performance over clarity this is the way:
// Remove double quotes at beginning and/or end of output
$len=strlen($output);
if($output[0]==='"') $iniidx=1; else $iniidx=0;
if($output[$len-1]==='"') $endidx=-1; else $endidx=$len-1;
if($iniidx==1 || $endidx==-1) $output=substr($output,$iniidx,$endidx);
The comment helps with clarity...
brackets in an array-like usage on strings is possible and demands less processing effort than equivalent methods, too bad there isnt a length variable or a last char index
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.)