tags:

views:

39

answers:

3

Am trying to use something like:

$newdata = preg_replace($pattern, $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?

A: 
$replacement = "START".$config."END"
Tomalak
A: 

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.

janmoesen
I have mentioned what it looks like.
Alec Smart
@Alec Smart: OK, in that case my solution should work.
janmoesen
A: 

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"
Progman