php
  • regex
  • 2010-11-28 53 views 4 likes 
    4

    我想從這個字符串正則表達式匹配成才與

    "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); 
    

    回答

    8

    丟失方括號:

    /^Dial/
    

    這匹配e字符串"Dial "在行首。

    僅供參考:您的原始正則表達式是一個反轉字符類[^...],它匹配任何不在該類中的字符。在這種情況下,它將匹配任何不是'D','i','a'或'l'的字符。由於幾乎每條線都至少具有不屬於其中的字符,因此幾乎每條線都會匹配。

    5

    我寧願使用strpos代替正則表達式:

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

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

    編輯:使用OP的字符串測試(一百萬次迭代)後,strpos比substr快大約30%,比preg_match快大約50%。

    +2

    不會substr($ a,0,4)==如果字符串中不存在'Dial'會更快(並且字符串非常長)? – 2010-11-28 03:57:17

    相關問題