php利用正則替換字符串的方法:1、使用preg_replace()函數(shù),語法“preg_replace(正則表達式,替換值,字符串)”;2、使用preg_filter()函數(shù),語法“preg_filter(正則表達式,替換值,字符串)”。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
php利用正則來替換字符串的兩種方法:
-
preg_replace()
-
preg_filter()
preg_replace() 和preg_filter()函數(shù)都可以執(zhí)行正則表達式的搜索和替換,不同的是 preg_filter() 函數(shù)只返回匹配成功的結(jié)果,而 preg_replace() 返回所有結(jié)果,不管是否匹配成功。
preg_replace() 和preg_filter()函數(shù)的語法類似:
preg_replace($pattern, $replacement, $subject [, $limit = -1 [, &$count]]) preg_filter($pattern, $replacement, $subject [, $limit = -1 [, &$count]])
搜索 $subject 中匹配 $pattern 的部分, 以 $replacement 進行替換。
參數(shù)說明如下:
-
$pattern:要搜索的模式,可以使一個字符串或字符串數(shù)組;
-
$replacement:用于替換的字符串或字符串數(shù)組。如果這個參數(shù)是一個字符串,并且 $pattern 是一個數(shù)組,那么所有的模式都使用這個字符串進行替換。如果 $pattern 和 $replacement 都是數(shù)組,每個 $pattern 使用 $replacement 中對應(yīng)的元素進行替換。如果 $replacement 中的元素比 $pattern 中的少,多出來的 $pattern 使用空字符串進行替換。
-
$subject:要進行搜索和替換的字符串或字符串數(shù)組,如果 $subject 是一個數(shù)組,搜索和替換回在 $subject 的每一個元素上進行, 并且返回值也會是一個數(shù)組。
-
$limit:可選參數(shù),每個模式在每個 $subject 上進行替換的最大次數(shù)。默認是 -1(無限)。
-
$count:可選參數(shù),如果指定,將會被填充為完成的替換次數(shù)。
示例:
preg_filter()和preg_replace()利用正則來替換字符串
<?php header('content-type:text/html;charset=utf-8'); $subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4'); $pattern = array('/d/', '/[a-z]/', '/[1a]/'); $replace = array('A:$0', 'B:$0', 'C:$0'); echo "preg_filter 返回值:n"; var_dump(preg_filter($pattern, $replace, $subject)); echo "preg_replace 返回值:n"; var_dump(preg_replace($pattern, $replace, $subject)); ?>
推薦學(xué)習(xí):《PHP視頻教程》