mansur
mansur

Reputation: 258

Regex to match specific words after one word

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

Answers (2)

Benjamin Poignant
Benjamin Poignant

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

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627419

To match all SEARCHWORDs 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.

PHP demo:

$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 SEARCHWORDs as whole words, enclose it with \bs (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

Related Questions