正则表达式匹配以。开头的东西

时间:2010-11-28 03:52:40

标签: 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 ..."

我想检查变量是否以字符串拨号

开头
$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 个答案:

答案 0 :(得分:8)

丢掉方括号:

/^Dial /

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

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

答案 1 :(得分:5)

我宁愿使用strpos而不是regexp:

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

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

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

相关问题