0

Let's say I have the following code:

$string = "Hello! This is a test. Hello this is a test!"

echo str_replace("Hello", "Bye", $string);

This will replace all Hello in $string with Bye. How can I e.g. exclude all where there's ! after Hello.

Means, I want this output: Hello! This is a test. Bye this is a test!

Is there a way in php to do that?

0

2 Answers 2

2

The solution using preg_repalce function with specific regex pattern:

$string = "Hello! This is a test. Hello this is a test!";
$result = preg_replace("/Hello(?!\!)/", "Bye", $string);

print_r($result);

The output:

Hello! This is a test. Bye this is a test!

(?!\!) - lookahead negative assertion, matches Hello word only if it's NOT followed by '!'

Sign up to request clarification or add additional context in comments.

Comments

1

You'll need a regular expression:

echo preg_replace("/Hello([^!])/", "Bye$1", $string);

[] is a character class and the ^ means NOT. So Hello NOT followed by !. Capture in () the NOT ! that is after Hello so you can use it in the replacement as $1 (first capture group).

Comments

Your Answer

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