简体   繁体   中英

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 elementum risus orci, ac tristique sem fringilla eget. risus orci,ac tristique sem fringilla eget。 Morbi maximus lectus nulla, sed tempor nibh condimentum ut. ut。 Sed tincidunt cursus nibh

I have tried this:

mb_ereg_replace('(?<=keyword)(.*?)(searchword)', '\1<b>\2</b>', $text, 'img');

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM