preg_filter
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
preg_filter — 執行一個正規表示式搜索和替換
說明
preg_filter(
mixed
mixed
mixed
int
int
): mixed
mixed
$pattern,mixed
$replacement,mixed
$subject,int
$limit = -1,int
&$count = ?): mixed
preg_filter()等價于preg_replace() 除了它僅僅返回(可能經過轉化)與目標匹配的結果. 這個函式怎樣工作的更詳細資訊請閱讀 preg_replace()文件.
返回值
如果subject是一個陣列,返回一個陣列,
其他情況返回一個字串。
如果沒有找到匹配或者發生了錯誤,當subject是陣列
時返回一個空陣列,其他情況返回null。
範例
示例 #1 比較preg_filter() 和preg_replace()的示例
<?php
$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 returns\n";
print_r(preg_filter($pattern, $replace, $subject));
echo "preg_replace returns\n";
print_r(preg_replace($pattern, $replace, $subject));
?>
以上例程會輸出:
preg_filter returns
Array
(
[0] => A:C:1
[1] => B:C:a
[2] => A:2
[3] => B:b
[4] => A:3
[7] => A:4
)
preg_replace returns
Array
(
[0] => A:C:1
[1] => B:C:a
[2] => A:2
[3] => B:b
[4] => A:3
[5] => A
[6] => B
[7] => A:4
)
參見
- PCRE 模式
- preg_quote() - 轉義正規表示式字元
- preg_replace() - 執行一個正規表示式的搜索和替換
- preg_replace_callback() - 執行一個正規表示式搜索並且使用一個回撥進行替換
- preg_grep() - 返回匹配模式的陣列條目
- preg_last_error() - 返回最後一個PCRE正則執行產生的錯誤程式碼