user3383675
user3383675

Reputation: 1081

PHP preg_replace is replacing too much

Code:

$string = "ABCD BEGIN LOL END ABCD";
$result = preg_replace("/BEGIN (.*?) END/","XD",$string);

Returns: ABCD XD ABCD, but I want to return ABCD BEGIN XD END ABCD,

How to do this correctly?

Upvotes: 1

Views: 153

Answers (3)

kevdev
kevdev

Reputation: 1124

You could use multiple capture groups and reinsert some content in your replacement:

<?php

$string = "ABCD BEGIN LOL END ABCD";
$result = preg_replace("/(BEGIN\s)(.*)(\sEND)/","$1XD$3",$string);
//Output is: ABCD BEGIN XD END ABCD
?>

Upvotes: 0

Mohit
Mohit

Reputation: 331

You can use it like follows

$string = "ABCD BEGIN LOL END ABCD";
$result = preg_replace("/LOL/","XD",$string);

Upvotes: 0

Gergo Erdosi
Gergo Erdosi

Reputation: 42043

You can use a positive lookbehind and lookahead:

$result = preg_replace("/(?<=BEGIN )(.*?)(?= END)/","XD",$string);

Upvotes: 8

Related Questions