PHP regexp用于“引用”;“字符串或模式的开头”;

PHP regexp用于“引用”;“字符串或模式的开头”;,php,regex,preg-match,Php,Regex,Preg Match,有没有一种方法(除了进行两个单独的模式匹配)在PHP中使用preg_match来测试字符串的开头或模式?更具体地说,我经常发现自己想要测试我是否有一个匹配模式,该模式前面没有任何东西,如 preg_match('/[^x]y/', $test) 预匹配(“/[^x]y/”,$test) (也就是说,如果y前面没有x,则匹配y),但如果y出现在$test的开头,则也匹配y(当y前面没有x,但前面没有任何字符时,[^x]构造将无法工作,因为它总是需要一个字符来匹配它 字符串结尾处也存在类似的问题,以

有没有一种方法(除了进行两个单独的模式匹配)在PHP中使用preg_match来测试字符串的开头或模式?更具体地说,我经常发现自己想要测试我是否有一个匹配模式,该模式前面没有任何东西,如

preg_match('/[^x]y/', $test) 预匹配(“/[^x]y/”,$test) (也就是说,如果y前面没有x,则匹配y),但如果y出现在$test的开头,则也匹配y(当y前面没有x,但前面没有任何字符时,[^x]构造将无法工作,因为它总是需要一个字符来匹配它


字符串结尾处也存在类似的问题,以确定是否出现了一个没有后跟其他模式的模式。

您可以简单地使用标准交替语法:

/(^|[^x])y/
这将匹配一个
y
,它前面有输入的开头或
x
以外的任何字符

当然,在这个特定的例子中,
^
锚定的替代方案非常简单,您也可以很好地使用:

/(?
$pattern='/^(?x)([a-z0-9]+)$(?
$pattern='/^(?!start)([a-z0-9]+)$(?
^开始了吗
及
$位于字符串的结尾处

这也是:
/(?<!x)y/
    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
Your Pattern is  :
 $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.
$name = "johnson";
preg_match("/^jhon..n$/",$name);