2010-10-20 62 views
1

什麼是一個字符串檢查單詞串

preg_match("/word/",$string) 

stripos("word",$string) 

來搜索詞的最好辦法還是有更好的辦法

+0

我想你自己給出了答案......這將是微觀最優化,如果你會使用另一個函數來檢查該字是否出現在字符串中。 – Harmen 2010-10-20 21:37:42

回答

6

使用正則表達式處理此作業的一個好處是可以在正則表達式中使用\bRegexp word boundary)以及其他隨機推導。如果您只是在字符串中尋找字母序列stripos很可能是更好。

$tests = array("word", "worded", "This also has the word.", "Words are not the same", "Word capitalized should match"); 
foreach ($tests as $string) 
{ 
    echo "Testing \"$string\": Regexp:"; 
    echo preg_match("/\bword\b/i", $string) ? "Matched" : "Failed"; 
    echo " stripos:"; 
    echo stripos("word", $string) >= 0 ? "Matched": "Failed"; 
    echo "\n"; 
} 

結果:

Testing "word": Regexp:Matched stripos:Matched 
Testing "worded": Regexp:Failed stripos:Matched 
Testing "This also has the word.": Regexp:Matched stripos:Matched 
Testing "Words are not the same": Regexp:Failed stripos:Matched 
Testing "Word capitalized should match": Regexp:Matched stripos:Matched 
+0

這是否包含像「同事」或「co」匹配的連字詞? – Joony 2010-10-20 21:57:02

+0

'-'和字母之間的點會匹配'\ b' - 所以'\ bwork'會匹配'同事' - 您可以使用[lookahead and lookbehind](http:// www.regular-expressions.info/lookaround.html) – gnarf 2010-10-20 22:02:23

1

對於簡單的字符串匹配的PHP字符串函數提供更高的性能。正則表達式更重,因此性能更低。儘管如此,在大多數情況下,性能差異足夠小,不會被注意到,除非您在具有數十萬個或更多元素的數組上循環播放。

當然,只要你開始需要「聰明」匹配,正則表達式就成爲鎮上唯一的遊戲。

2

如果您只是在尋找子字符串,stripos()strpos()和朋友比使用preg功能家族好得多。

0

還有substr_count($haystack, $needle)剛剛返回字符串出現次數的數量。如果第一次出現在位置0,則不需要擔心0等於false,如stripos()的附加獎勵。儘管如果使用嚴格的相等性,這不是問題。

http://php.net/manual/en/function.substr-count.php

4

像它說在Notes爲preg_match

不要使用的preg_match(),如果你只是想檢查一個字符串包含在另一個字符串。使用strpos()或strstr()來代替,因爲它們會更快。

+0

strstr()函數區分大小寫。 – 2010-11-08 06:47:30

+0

@Harish所以呢?如果您需要區分大小寫,請使用'stristr'或'stripos'。 – Gordon 2010-11-08 07:57:23

+0

但stripos()函數將返回字符串中字母的位置,所以它在上述情況下沒有用處.. @Gordon – 2010-11-08 09:37:01