Reputation: 1081
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
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
Reputation: 331
You can use it like follows
$string = "ABCD BEGIN LOL END ABCD";
$result = preg_replace("/LOL/","XD",$string);
Upvotes: 0
Reputation: 42043
You can use a positive lookbehind and lookahead:
$result = preg_replace("/(?<=BEGIN )(.*?)(?= END)/","XD",$string);
Upvotes: 8