开发者

PHP preg_replace without eval

开发者 https://www.devze.com 2023-01-02 07:40 出处:网络
Am trying to use something like: $newdata = preg_replace($开发者_如何学Pythonpattern, $replacement, $data);

Am trying to use something like:

$newdata = preg_replace($开发者_如何学Pythonpattern, $replacement, $data);

Now my replacement is something like

$pattern = "/START(.*?)END/is";
$replacement = "START $config END";

Now, $config contains contents like

array('Test\\\'s Page')

The problem is that after I write the content, $newdata becomes

START array('Test\\'s Page') END

As you see above a single \ goes missing because it gets evaluated. How do I avoid that?


This works as expected... at least according to the manual of preg_replace.

To use backslash in replacement, it must be doubled ("\\\\" PHP string).

This is needed as you can use \\n for back references. If you don't want a back reference but want the \ itself you need to escape it. If you want 3 backslashes you must write 6 backslashes.

$data = 'Some START END testdata';
$config = 'array(\'Test\\\\\\\\\\\\\'s Page\')';
$replacement = "START $config END";
$pattern = "/START(.*?)END/is";
var_dump($data, $config, $replacement, $pattern);
$newdata = preg_replace($pattern, $replacement, $data);
var_dump($newdata);

This will generate the following output.

string(23) "Some START END testdata"
string(26) "array('Test\\\\\\'s Page')"
string(36) "START array('Test\\\\\\'s Page') END"
string(17) "/START(.*?)END/is"
string(47) "Some START array('Test\\\'s Page') END testdata"


$replacement = "START".$config."END"


Have you tried flattening the array into a string?

$replacement = sprintf('START %s END', implode('', $config));

EDIT: Since you did not mention what the $config looks like, we cannot give a definite answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消