探討PHP函數(shù)preg_split()的功能實(shí)現(xiàn)
我們在前面曾靜為大家介紹過有關(guān)split函數(shù)的相關(guān)功能,在接下來這篇文章中,我們將會具體介紹一種功能與其相似的函數(shù),PHP函數(shù)preg_split()的相關(guān)使用方法。代碼6.9是一個(gè)查找文章中單詞數(shù)量的示例。
PHP函數(shù)preg_split()代碼6.9 查找文章中單詞數(shù)量
- < ?php
- $seek = array();
- $text = "I have a dream that one day
I can make it. So just do it, nothing is impossible!";- //將字符串按空白,標(biāo)點(diǎn)符號拆分(每個(gè)標(biāo)點(diǎn)后
也可能跟有空格)- $words = preg_split("/[.,;!\s']\s*/", $text);
- foreach($words as $val)
- {
- $seek[strtolower($val)] ++;
- }
- echo "共有大約" .count($words). "個(gè)單詞。";
- echo "其中共有" .$seek['i']. "個(gè)單詞“I”。";
- ?>
#t#PHP函數(shù)preg_split()使用了Perl兼容正則表達(dá)式語法,通常是比split()更快的替代方案。使用正則表達(dá)式的方法分割字符串,可以使用更廣泛的分隔字符。例如,上面對日期格式和單詞處理的分析。如果僅用某個(gè)特定的字符進(jìn)行分割,建議使用explode()函數(shù),它不調(diào)用正則表達(dá)式引擎,因此速度是最快的。