正则表达式匹配开头的某些内容

Har*_*M V 4 php regex

我想从这个字符串中获得一个匹配

"Dial [Toll Free 1800 102 8880 ext: 246] to connect to the restaurant.  <a class='tooltip' title='Foodiebay has now introduced value added calling features through the website. You just need to dial this number and we ..."
Run Code Online (Sandbox Code Playgroud)

我想检查变量是否以字符串Dial开头

$a = 'Dial [Toll Free 1800 102 8880 ext: 246] to connect to the restaurant.  <a class='tooltip' title='Foodiebay has now introduced value added calling features through the website. You just need to dial this number and we';

preg_match('/[^Dial]/', $a, $matches);
Run Code Online (Sandbox Code Playgroud)

Mar*_*tos 8

丢掉方括号:

/^Dial /
Run Code Online (Sandbox Code Playgroud)

这匹配"Dial "行开头的字符串.

仅供参考:您的原始正则表达式是一个倒置字符类[^...],它匹配类中没有的任何字符.在这种情况下,它将匹配任何不是'D','i','a'或'l'的字符.由于几乎每一行都至少具有不是其中一个的字符,因此几乎每一行都匹配.


Vin*_*ard 5

我宁愿使用strpos而不是正则表达式:

if (strpos($a, 'Dial') === 0) {
    // ...
Run Code Online (Sandbox Code Playgroud)

===很重要,因为它也可能返回false.(false == 0)是真的,但却 (false === 0)是假的.

编辑:在使用OP的字符串进行测试(一百万次迭代)之后,strpos比substr快约30%,比preg_match快约50%.

  • 如果字符串中不存在(并且字符串很长),那么substr($ a,0,4)=='D​​ial'会更快吗? (2认同)