Skip to content
Advertisement

php preg_replace strings with brackets

I am trying to replace some text if it isn’t preceded with a dot (.), but my function seems to result include an unexpected slash …

<?php

$test="function insertXYZ(e){e.insertXYZ()};";
$search="insertXYZ(";
$replace="zzzz(";

$search=str_replace("(", '(', $search);
//echo $search."nn";
$pattern = 'b' . $search;
$replaceException="999";

$test=preg_replace('/' . ".".$pattern . '/', "$replaceException", $test);
$test=preg_replace('/' . $pattern . '/', $replace, $test);
$test=preg_replace('/' . $replaceException . '/', ".$search", $test);

echo $test;
?>

A sample of this code can be found at http://sandbox.onlinephpfunctions.com/code/24cab4eece20d22a11dd887da44d63e393b51aa9

which outputs…

function zzzz(e){e.insertXYZ()};
                            ^

but I want the output to read…

function zzzz(e){e.insertXYZ()};
                            ^

Where am I going wrong?

Advertisement

Answer

It’s because in this line, you’re adding the backslash and then never remove it

$search=str_replace("(", '(', $search);

You could change your code to the following so that you don’t need to manually escape this bracket.

// $search=str_replace("(", '(', $search); <-- Removed
$pattern = 'b' . preg_quote($search);

However, you could get the same output with much less code

$testString = "function insertXYZ(e){e.insertXYZ()};";
$regex = "/[^.](insertXYZ)/s";
echo(preg_replace($regex, " zzzz", $testString));
[^.] - Character group looking where there's NOT a dot character
(insertXYZ) - matches 'insertXYZ' exactly (case sensitive)
/s - Single line modifier so there's no need to escape the dot character
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement