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