PHP正则表达式用于“字符串开头或模式”的匹配

5
除了进行两个单独的模式匹配之外,是否有其他方法(在PHP中使用preg_match)来测试字符串的开头或模式?更具体地说,我经常想要测试我是否有一个匹配的模式,它不是以某些内容为前提的,比如 preg_match('/[^x]y/', $test)
(也就是说,如果y没有被x所限制,则匹配y)。但同时也要匹配$test开头的y,因为它也没有被x限制,但却没有任何字符作为其前缀,所以[^x]构造将无法起到作用,因为它总需要与某个字符匹配。在字符串结束时也存在类似的问题,以确定是否存在某种模式,而此模式后面没有跟随其他模式。

还有这个:https://dev59.com/Y3A75IYBdhLWcg3w0cjx - Kobi
3个回答

10

您可以直接使用标准交替语法:

/(^|[^x])y/

这将匹配一个y,该y要么位于输入的开头,要么前面是除了x以外的任何字符。

当然,在这种特定情况下,如果与^锚点相比,另一种选择非常简单,您也可以使用否定的后顾断言

/(?<!x)y/

1
$name = "johnson";
preg_match("/^jhon..n$/",$name);

^表示字符串的开头位置,$表示字符串的结尾位置。


0
    You need following negate rules:-

--1--^(?!-) is a negative look ahead assertion, ensures that string does not start with specified chars

--2--(?<!-)$ is a negative look behind assertion, ensures that string does not end with specified chars

假设你想要一个不以 'start' 开头且以 'end' 结尾的字符串:

Your Pattern is  :

$pattern = '/^(?!x)([a-z0-9]+)$(?

 $pattern = '/^(?!start)([a-z0-9]+)$(?<!end)/';

$strArr = array('start-pattern-end','allpass','start-pattern','pattern-end');


 foreach($strArr as $matstr){ 
     preg_match($pattern,$matstr,  $matches);
     print_R( $matches);
 }

This will output :allpass only as it doen't start with 'start' and end with 'end' patterns.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接