正则表达式匹配以某个字符串开头的内容

5

我正在尝试从这个字符串中获取匹配项

"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 ..."

我想要检查一个变量是否以字符串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);
2个回答

10

去掉方括号:

/^Dial /

这个正则表达式匹配了一行开头的字符串"Dial "

顺便说一下:你原来的正则表达式是一个反向字符类[^...],它匹配任何不在该类别中的字符。在这种情况下,它将匹配任何不是 'D'、'i'、'a' 或 'l' 的字符。由于几乎每一行都至少有一个不属于这些字符的字符,所以几乎每一行都会匹配。


6

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

if (strpos($a, 'Dial') === 0) {
    // ...

===非常重要,因为它也可以返回false。 (false == 0)是true,但(false === 0)是false。

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


2
如果字符串中不存在substr($a,0,4) == 'Dial',那么这样做会更快吗?(尤其是当字符串非常长时) - Stefan Mai
1
@Stefan Mai:我不知道它是否更快,但它看起来也是一个不错的解决方案。 - Vincent Savard

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