描述
假设您的用例要复杂一些hello, i said <a>hello</a>
;然后,如果您在哪里寻找所有内容hello
,hello, i said <a>after arriving say hello</a>
您可能只想捕捉好的和坏的,然后使用一些编程逻辑来仅处理您感兴趣的匹配项。
此表达式将捕获所有<a>...</a>
子字符串和所有hello
字符串。由于如果需要的子字符串出现在内部,则首先匹配不需要的子字符串,因此它永远不会包含在捕获组 1 中。
<a>.*?<\/a>|\b(hello)\b

例子
现场示例:http: //ideone.com/jpcqSR
示例文本
Chello said Hello, i said <a>after arriving say hello</a>
代码
$string = 'Chello said Hello, i said <a>after arriving say hello</a>';
$regex = '/<a>.*?<\/a>|\b(hello)\b/ims';
preg_match_all($regex, $string, $matches);
foreach($matches as $key=>$value){
if ($value[1]) {
echo $key . "=" . $value[0];
}
}
输出
请注意 hello 中的大写字母H
表明它是所需的子字符串。
0=Hello