Reputation: 258
So I have the following sample:
Lorem ipsum dolor SEARCHWORD sit amet, consectetur adipiscing elit. Fusce lacus nisl, feugiat laoreet dignissim sit amet, KEYWORD gravida vel velit. Nunc SEARCHWORD elementum risus orci, ac tristique sem fringilla SEARCHWORD eget. Morbi maximus lectus nulla, sed tempor nibh SEARCHWORD condimentum ut. Sed tincidunt cursus nibh
I want to match all the SEARCHWORD
after the KEYWORD
and replace them with surrounding Tags like <b>SEARCHWORD</b>
. Have been trying and searching for one Day now... Is that even possible with regular expressions? If yes, does anybody have an idea how to solve this with a regex?
So, I am looking to match all SEARCHWORDs after the first occurrence of KEYWORD in the string. The expected output is:
Lorem ipsum dolor SEARCHWORD sit amet, consectetur adipiscing elit. Fusce lacus nisl, feugiat laoreet dignissim sit amet, KEYWORD gravida vel velit. Nunc SEARCHWORD elementum risus orci, ac tristique sem fringilla SEARCHWORD eget. Morbi maximus lectus nulla, sed tempor nibh SEARCHWORD condimentum ut. Sed tincidunt cursus nibh
I have tried this:
mb_ereg_replace('(?<=keyword)(.*?)(searchword)', '\1<b>\2</b>', $text, 'img');
Upvotes: 4
Views: 533
Reputation: 1064
You do not have to pass 'img' as options. See this reference page.
var_dump(mb_ereg_replace('.*?(keyword).*?(searchword).*?$', '\1<b>\2</b>', 'AAAAAAAAkeywordBBBBBBBCCCCCCsearchwordDDDDDD'));
//output : string 'keyword<b>searchword</b>' (length=24)
Upvotes: 1
Reputation: 627419
To match all SEARCHWORD
s after the first occurrence of KEYWORD
in the string, you can use a \G
based regex like
(?:KEYWORD|(?!^)\G).*?\KSEARCHWORD
See the regex demo
The (?:KEYWORD|(?!^)\G)
matches the first KEYWORD
and then (?!^)\G
requires the next match to appear right at the location of the previous match.
The .*?
matches 0+ any characters (since the regex is to be used with DOTALL /s
option) as few as possible up to the first SEARCHWORD
, and \K
omits the whole match value up to the search word.
$re = '~(?:KEYWORD|(?!^)\G).*?\KSEARCHWORD~su';
$str = "Lorem ipsum dolor SEARCHWORD sit amet, consectetur adipiscing elit. Fusce lacus nisl, feugiat laoreet dignissim sit amet, KEYWORD gravida vel velit. Nunc SEARCHWORD elementum risus orci, ac tristique sem fringilla SEARCHWORD eget. Morbi maximus lectus nulla, sed tempor nibh SEARCHWORD condimentum ut. Sed tincidunt cursus nibh";
$result = preg_replace($re, "<b>SEARCHWORD</b>", $str);
echo $result;
NOTE: If you need to search for SEARCHWORD
s as whole words, enclose it with \b
s (if the search word consists of alphanumeric / _
characters), or with (?<!\w)
and (?!\w)
if the leading/trailing characters may be non-word characters.
Upvotes: 4