我想从这个字符串中获得一个匹配
"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)
丢掉方括号:
/^Dial /
Run Code Online (Sandbox Code Playgroud)
这匹配"Dial "行开头的字符串.
仅供参考:您的原始正则表达式是一个倒置字符类[^...],它匹配类中没有的任何字符.在这种情况下,它将匹配任何不是'D','i','a'或'l'的字符.由于几乎每一行都至少具有不是其中一个的字符,因此几乎每一行都匹配.
我宁愿使用strpos而不是正则表达式:
if (strpos($a, 'Dial') === 0) {
// ...
Run Code Online (Sandbox Code Playgroud)
===很重要,因为它也可能返回false.(false == 0)是真的,但却 (false === 0)是假的.
编辑:在使用OP的字符串进行测试(一百万次迭代)之后,strpos比substr快约30%,比preg_match快约50%.