0

Is it possible to create a regular expression of a pattern X that is not enclosed by a pattern Y using preg_match in PHP?

for example, consider this string:

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

I want a regex that matches the first hello but not the second... I couldn't think of anything

4

2 回答 2

1

在查找后面使用否定查找:

(?<!<a>)hello
于 2013-07-07T12:26:46.623 回答
0

描述

假设您的用例要复杂一些hello, i said <a>hello</a>;然后,如果您在哪里寻找所有内容hellohello, 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
于 2013-07-08T03:57:51.040 回答