user6790913
user6790913

Reputation:

PHP str_replace; check for more than the replace part

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?

Upvotes: 0

Views: 248

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

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).

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

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 '!'

Upvotes: 2

Related Questions