小白教程
所有教程
关于
Search
172.70.127.104
172.70.127.104
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Php preg replace”的源代码
本页内容
上一节:
Php_preg_replace_callback
下一节:
Php_preg_split
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:preg_replace}}[[Category:PHP正则表达式(PCRE)|9]] = PHP preg_replace() 函数 = [[:Category:PHP正则表达式(PCRE)]] preg_replace 函数执行一个正则表达式的搜索和替换。 === 语法 === <sample title="" desc="" lang="php" hererun="1"> mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) </sample> 搜索 subject 中匹配 pattern 的部分, 以 replacement 进行替换。 参数说明: * $pattern: 要搜索的模式,可以是字符串或一个字符串数组。 * $replacement: 用于替换的字符串或字符串数组。 * $subject: 要搜索替换的目标字符串或字符串数组。 * $limit: 可选,对于每个模式用于每个 subject 字符串的最大可替换次数。 默认是-1(无限制)。 * $count: 可选,为替换执行的次数。 === 返回值 === 如果 subject 是一个数组, preg_replace() 返回一个数组, 其他情况下返回一个字符串。 如果匹配被查找到,替换后的 subject 被返回,其他情况下 返回没有改变的 subject。如果发生错误,返回 NULL。 == == 将 google 替换为 xiaobai == <sample title="" desc="" lang="php" hererun="1"> <?php $string = 'google 123, 456'; $pattern = '/(\w+) (\d+), (\d+)/i'; $replacement = 'xiaobai ${2},$3'; echo preg_replace($pattern, $replacement, $string); ?> </sample> 执行结果如下所示: <sample title="" desc="" lang="php" hererun="1"> xiaobai 123,456 </sample> == 删除空格字符 == <sample title="" desc="" lang="php" hererun="1"> <?php $str = 'runo o b'; $str = preg_replace('/\s+/', '', $str); // 将会改变为'xiaobai' echo $str; ?> </sample> 执行结果如下所示: <sample title="" desc="" lang="php" hererun="1"> xiaobai </sample> == 使用基于数组索引的搜索替换 == <sample title="" desc="" lang="php" hererun="1"> <?php $string = 'The quick brown fox jumped over the lazy dog.'; $patterns = array(); $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements = array(); $replacements[2] = 'bear'; $replacements[1] = 'black'; $replacements[0] = 'slow'; echo preg_replace($patterns, $replacements, $string); ?> </sample> 执行结果如下所示: <sample title="" desc="" lang="php" hererun="1"> The bear black slow jumped over the lazy dog. </sample> == 使用参数 count == <sample title="" desc="" lang="php" hererun="1"> <?php $count = 0; echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count); echo $count; //3 ?> </sample> 执行结果如下所示: <sample title="" desc="" lang="php" hererun="1"> xp***to 3 </sample> [[:Category:PHP正则表达式(PCRE)]]
返回至“
Php preg replace
”。
上一节:
Php_preg_replace_callback
下一节:
Php_preg_split