RegEx:匹配Y未包含的所有X出现

时间:2013-07-07 12:23:35

标签: php regex preg-match

是否可以在PHP中使用preg_match创建未被模式Y包围的模式X的正则表达式?

例如,考虑这个字符串:

hello, i said <a>hello</a>

我想要一个匹配第一个你好但不是第二个的正则表达式...我想不出任何东西

2 个答案:

答案 0 :(得分:1)

在查找后面使用负面看法:

(?<!<a>)hello

答案 1 :(得分:0)

描述

假设您的用例比hello, i said <a>hello</a>稍微复杂一点;然后,如果您在hello寻找hello, i said <a>after arriving say hello</a>中的所有<a>...</a>,您可能只想捕获好的和坏的,那么使用一些编程逻辑来处理您感兴趣的匹配。

此表达式将捕获所有hello子字符串和所有<a>.*?<\/a>|\b(hello)\b字符串。由于不期望的子字符串首先匹配,如果所需的子字符串出现在内部,那么它将不会被包含在捕获组1中。

Chello said Hello, i said <a>after arriving say hello</a>

enter image description here

实施例

实例:http://ideone.com/jpcqSR

示例文字

$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];
    }
        }

<强>代码

H

<强>输出

请注意hello中的大写0=Hello 表示它是所需的子字符串。

{{1}}