When running a function which returns a string, I end up with backwards-slashes before a quotation marks, like this:
$string = get_string();
// returns: Example
I suspect it is some type of escaping happening somewhere. I know I can string replace the backwards-slash, but I suppose in these cases, there is some type of unescape function you run?
You only need to escape quotes when it matches your starting/ending delimiter. This code should work properly:
$string = 'Example';
If your string is enclosed in single quotes ', then " doesn't need to be escaped. Likewise, the opposite is true.
Avoid using stripslashes(), as it could cause issues if single quotes need to contain slashes. A simple find/replace should work for you:
$string = 'Example';
$string = str_replace($string, '\"', '"');
echo $string; //echos Example
<?php
$string = 'Example';
echo stripslashes($string);
?>
Related
$str = "{Controller}/{Action}";
$str = preg_replace("/\//","\\/",$str);
$str = preg_replace("/(\{\w+\})\\/(\{\w+\})/","\\1 slash \\2",$str);
echo $str;
So the third line doesn't do anything for me, could anyone say where i was wrong? It works if i put something else instead of \/
thanks in advance;)
This will work:
$str = "{Controller}/{Action}";
$str = preg_replace('#(\{\w+\})/(\{\w+\})#', '\1 slash \2', $str);
echo $str;
Output: {Controller} slash {Action}
Remarks:
You should use single quotes to reduce the need for escaping and therefore much better readability.
You also should consider using another delimiter if you are matching literal slashes (eg #, but anything works)
To get a double quoted string (which I cannot change) correctly parsed I have to do following:
$string = '15 Rose Avenue\n Irlam\n Manchester';
$string = str_replace('\n', "\n", $string);
print nl2br($string); // demonstrates that the \n's are now linebreak characters
So far, so good.
But in my given string there are characters like \xC3\xA4. There are many characters like this (beginning with \x..)
How can I get them correctly parsed as shown above with the linebreak?
You can use
$str = stripcslashes($str);
You can escape a \ in single quotes:
$string = str_replace('\\n', "\n", $string);
But you're going to have a lot of potential replaces if you need to do \\xC3, etc.... best use a preg_replace_callback() with a function(callback) to translate them to bytes
After having some trouble building a json string I discovered some text in my database containing double quotes. I need to replace the quotes with their escaped equivalents. This works:
function escape( $str ) {
return preg_replace('/"/',"\\\"",$str);
}
but it doesn't take into account that a quote may already be escaped. How can I modify the expression so that it's only true only for a non escaped character?
You need to use a negative lookbehind here
function escape( $str ) {
return preg_replace('/(?<!\\)"/',"\\\"",$str);
}
Try first remove the '\' from all escaped doube-quotes, than escape all double-quotes.
str_replace(array('\"', '"'), array('"', '\"'), $str);
Try preg_replace('/([^\\\])"/', '$1\\"', $str);
I believe this will work
regex:
(?<!\\)((?:\\\\)*)"
code:
$re = '/(?<!\\\\)((?:\\\\\\\\)*)"/';
preg_replace($re, '$1\\"', 'foo"bar'); // foo\"bar -- slash added
preg_replace($re, '$1\\"', 'foo\\"bar'); // foo\"bar -- already escaped, nothing added
preg_replace($re, '$1\\"', 'foo\\\\"bar'); // foo\\\"bar -- not escaped, extra slash added
I’m trying to modify a string of the following form where each field is delimited by a tab except for the first which is followed by two or more tabs.
"$str1 $str2 $str3 $str4 $str5 $str6"
The modified string will have each field wrapped in HTML table tags, and be on its own, indented line as so.
"<tr>
<td class="title">$str1</td>
<td sorttable_customkey="$str2"></td>
<td sorttable_customkey="$str3"></td>
<td sorttable_customkey="$str4"></td>
<td sorttable_customkey="$str5"></td>
<td sorttable_customkey="$str6"></td>
</tr>
"
I tried using code like the following to do it.
$patterns = array();
$patterns[0]='/^/';
$patterns[1]='/\t\t+/';
$patterns[2]='/\t/';
$patterns[3]='/$/';
$replacements = array();
$replacements[0]='\t\t<tr>\r\n\t\t\t<td class="title">';
$replacements[1]='</td>\r\n\t\t\t<td sorttable_customkey="';
$replacements[2]='"></td>\r\n\t\t\t<td sorttable_customkey="';
$replacements[3]='"></td>\r\n\t\t</tr>\r\n';
for ($i=0; $i<count($lines); $i++) {
$lines[$i] = preg_replace($patterns, $replacements, $lines[$i]);
}
The problem is that the escaped characters (tabs and newlines) in the replacement array remain escaped in the destination string and I get the following string.
"\t\t<tr>\r\n\t\t\t<td class="title">$str</td>\r\n\t\t\t<td sorttable_customkey="$str2"></td>\r\n\t\t\t<td sorttable_customkey="$str3"></td>\r\n\t\t\t<td sorttable_customkey="$str4"></td>\r\n\t\t\t<td sorttable_customkey="$str5"></td>\r\n\t\t\t<td sorttable_customkey="$str6"></td>\r\n\t\t</tr>\r\n"
Strangely, this line I tried earlier on does work:
$data=preg_replace("/\t+/", "\t", $data);
Am I missing something? Any idea how to fix it?
You need double quotes or heredocs for the replacement string - PCRE only parses those escape characters in the search string.
In your working example preg_replace("/\t+/", "\t", $data) those are both literal tab characters because they're in double quotes.
If you changed it to preg_replace('/\t+/', '\t', $data) you can observe your main problem - PCRE understands that the \t in the search string represents a tab, but doesn't for the one in the replacement string.
So by using double quotes for the replacement, e.g. preg_replace('/\t+/', "\t", $data), you let PHP parse the \t and you get the expected result.
It is slightly incongruous, just something to remember.
Your $replacements array has all its strings decalred as single-quoted strings.
That means that escaped characters won't scape (except \').
It is not related directly to PCRE regular expressions, but to how PHP handles strings.
Basically you can type strings like these:
<?php # String test
$value = "substitution";
$str1 = 'this is a $value that does not get substituted';
$str2 = "this is a $value that does not remember the variable"; # this is a substitution that does not remember the variable
$str3 = "you can also type \$value = $value" # you can also type $value = substitution
$bigstr =<<< MARKER
you can type
very long stuff here
provided you end it with the single
value MARKER you had put earlier in the beginning of a line
just like this:
MARKER;
tl;dr version: problem is single quotes in the $replacements and $patterns that should be double quotes
I have a string like this: foo($bar1, $bar2)
How to I replace each variable with <span>$variable</span> with regexp?
This is my try (not working):
$row['name'] = preg_replace("/\$\w+/S", "<span>$1</span>", $row['name']);
I only want the variables to be replaced and have a span around them, I don't want commas or spaces to be replaced.
What I want is to have my string foo($bar1, $bar2) to be replaced with foo(<span>$bar1</span>, <span>$bar2</span>) ($bar1 and $bar2 are not variables, it's plain text).
Here are some problems I can see:
Since you are using double quotes for the regex,
you need to escape the $ using two \ as \\$.
Alternatively you can just use single
quote and use \$.
You are using $1 in the replacement
but you are not having any group in
the regex. So have ( ) around
\$\w+
So try:
$str = preg_replace('/(\$\w+)/', "<span>$1</span>", $str);
or
$str = preg_replace("/(\\$\w+)/", "<span>$1</span>", $str);
See it.