0

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."\n\n";
$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?

2
  • You're losing sight of your values as you go. Output/inspect the variable values after each step, and you'll see why the value of $search with the backslash in it is being placed into your final value. Commented Apr 21, 2021 at 18:32
  • Use this to automatically escape your search string: php.net/manual/en/function.preg-quote.php Commented Apr 21, 2021 at 19:58

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Lucan; I notice on your "much less code" version, you put in a space before the zzzz; is there any way to avoid this (as the $testString might not have a preceding space). Also - what if the line started with "insertXYZ" (as opposed to "function insertXYZ")?
I added the space to keep the code short as an example but otherwise, you would need to modify the regex so that it could replace only the first group, not the whole match. Regex has a special start of line identifier ^ which you can use to signify the start.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.