Monday 1 January 2018

php - Warning: Unexpected character in input: '' (ASCII=92) state=1

itemprop="text">

I receive the following error
message:



Warning: Unexpected
character in input: '\' (ASCII=92)
state=1


And this is
the line of code that is giving me this
trouble.




$tag_value =
preg_replace('/\{(.*?)\}/e', '$values[\\1]',
$tag_value);


I am
using PHP 5.2.9 and upgrading is not an
option.



Regular expression are not my specialty
and I am not able to solve this problem on my own. Any help would be greatly
appreciated.


itemprop="text">
class="normal">Answer



You cannot
accomplish this with a simple preg_replace, as array
de-referencing is not done with /e modifier. Instead you can
use preg_replace_callback
function:



$tag_value =
preg_replace_callback("/\{(.*?)\}/", function($m) use($values){


return $values[$m[1]];
},
$tag_value);


This
definitely works in php 5.3, however in 5.2 you may need to define the callback function
explicitly:



function replace($m)
{
global $values;
return
$values[$m[1]];
}

$tag_value =
preg_replace_callback("/\{(.*?)\}/", "replace",
$tag_value);


EDIT:
The error you are seeing is happening because with your original code, your substitution
is being treated literally as $values[\1] (after unescaping the
backslash - in this string, \1 is not the right stuff to put
inside the brackets.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...