摘要:資源收錄正則函數(shù)注不同于字符串函數(shù),為主動(dòng)傳值,指示替換次數(shù)匯集全網(wǎng)優(yōu)質(zhì)網(wǎng)址及資源的中文上網(wǎng)導(dǎo)航。要注意替換順序,如果先將網(wǎng)址替換為標(biāo)簽,再去除所有標(biāo)簽,會(huì)將鏈接也去除其他正則函數(shù)帶回調(diào)函數(shù)匯集全網(wǎng)優(yōu)質(zhì)網(wǎng)址導(dǎo)航。
1.字符串匹配與查找
a.如果可以使用字符串處理函數(shù)處理的,不要使用正則表達(dá)式(功能強(qiáng),效率低)
b.使用正則表達(dá)式匹配函數(shù):
(1)preg_match:匹配用戶名/email/url
"; } if(!preg_match("/w+([+-.]w+)*@w+([-.]w+)*.w+([-.]w+)*/i",$_POST["email"])){ echo "不是正確的email格式
"; } if(!preg_match("/(https?|fps?)://(www|mail|bbs|fps).(.*?).(net|com|org|cn)([w+./=?&\%]*)?/",$_POST["url"],$arr)){ echo "不是正確的url格式
"; }else{ echo ""; print_r($arr); echo ""; /* Array ( [0] => https://www.baidu.com/ [1] => https [2] => www [3] => baidu [4] => com [5] => / )*/ } } ?>
(2)preg_match_all:以匹配url為例展示,可以匹配全部url,返回多維數(shù)組(視子模式而定),可以傳入第四個(gè)參數(shù),以改變多維數(shù)組的構(gòu)成模式
"; }else{ echo ""; print_r($arr); echo ""; /* Array ( [0] => Array ( [0] => http://www.liuxue86.com/a/3101593.html [1] => https://www.segmentfault.com/write?draftId=1220000010640798 ) [1] => Array ( [0] => http [1] => https ) [2] => Array ( [0] => www [1] => www ) [3] => Array ( [0] => liuxue86 [1] => segmentfault ) [4] => Array ( [0] => com [1] => com ) [5] => Array ( [0] => /a/3101593.html [1] => /write?draftId=1220000010640798 ) )*/ } ?>
(3)preg_grep:對(duì)多個(gè)字符串的數(shù)組進(jìn)行匹配,如下:
1111111111 [3] => 2222222222 ) ?>
c.使用字符串匹配函數(shù):strstr/strpos/substr
function getFileName($url){ $str=strrpos($url,"/")+1; return substr($url,$str); } echo getFileName("https://segmentfault.com/write?draftId=1220000010640798/aaa.php");
2.字符串的分割與連接
a.使用字符串函數(shù):explode/implode/join
b.使用正則函數(shù):preg_split ( $pattern , $subject [,$limit = -1 [,$flags = 0 ]] ),其中l(wèi)imit為分割的總個(gè)數(shù)(即數(shù)組長(zhǎng)度),-1表示不限制個(gè)數(shù),flags為可選系統(tǒng)參數(shù)
注:字符偏移量為該字符相對(duì)于首字符的位置
aaaaaa [1] => bbbbb. ccccccc ) ?>
3.字符串的替換
a.字符串函數(shù):str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ),&$count返回替換次數(shù),由于混合類型,因此可以以數(shù)組替換數(shù)組,如下:
"; echo $count; ?>
b.正則函數(shù):mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
*注1*:&$count不同于字符串函數(shù),為主動(dòng)傳值,指示替換次數(shù)
網(wǎng)址及資源
的中文上網(wǎng)導(dǎo)航。及時(shí)收錄影視、音樂、小說、游戲等分類的網(wǎng)址和內(nèi)容,讓您的網(wǎng)絡(luò)生活更簡(jiǎn)單精彩。"; $result=preg_replace("/<[/!]*?[^<>]*?>/is","",$str,1);//替換HTML標(biāo)簽,只替換了一次 echo $result."
"; ?>
*注2*:替換項(xiàng)$replacement可以使用12等借用正則中子模式的內(nèi)容,如下: