Home > Backend Development > PHP Problem > php replace regular replacement method

php replace regular replacement method

藏色散人
Release: 2023-03-11 17:00:02
Original
5937 people have browsed it

php replace函数用于执行一个正则表达式的搜索和替换,其使用语法是“mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject...”。

php replace regular replacement method

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php replace正则替换方法

preg_replace 函数执行一个正则表达式的搜索和替换。

语法

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Copy after login

搜索 subject 中匹配 pattern 的部分, 以 replacement 进行替换。

参数说明:

$pattern: 要搜索的模式,可以是字符串或一个字符串数组。

$replacement: 用于替换的字符串或字符串数组。

$subject: 要搜索替换的目标字符串或字符串数组。

$limit: 可选,对于每个模式用于每个 subject 字符串的最大可替换次数。 默认是-1(无限制)。

$count: 可选,为替换执行的次数。

返回值

如果 subject 是一个数组, preg_replace() 返回一个数组, 其他情况下返回一个字符串。

如果匹配被查找到,替换后的 subject 被返回,其他情况下 返回没有改变的 subject。如果发生错误,返回 NULL。

实例

将 google 替换为 runoob

<?php
$string = &#39;google 123, 456&#39;;
$pattern = &#39;/(\w+) (\d+), (\d+)/i&#39;;
$replacement = &#39;runoob ${2},$3&#39;;
echo preg_replace($pattern, $replacement, $string);
?>
Copy after login

执行结果如下所示:

runoob 123,456
Copy after login

删除空格字符

<?php
$str = &#39;runo o   b&#39;;
$str = preg_replace(&#39;/\s+/&#39;, &#39;&#39;, $str);
// 将会改变为&#39;runoob&#39;
echo $str;
?>
Copy after login

执行结果如下所示:

runoob
Copy after login

使用基于数组索引的搜索替换

<?php
$string = &#39;The quick brown fox jumped over the lazy dog.&#39;;
$patterns = array();
$patterns[0] = &#39;/quick/&#39;;
$patterns[1] = &#39;/brown/&#39;;
$patterns[2] = &#39;/fox/&#39;;
$replacements = array();
$replacements[2] = &#39;bear&#39;;
$replacements[1] = &#39;black&#39;;
$replacements[0] = &#39;slow&#39;;
echo preg_replace($patterns, $replacements, $string);
?>
Copy after login

执行结果如下所示:

The bear black slow jumped over the lazy dog.
Copy after login

使用参数 count

<?php
$count = 0;
 
echo preg_replace(array(&#39;/\d/&#39;, &#39;/\s/&#39;), &#39;*&#39;, &#39;xp 4 to&#39;, -1 , $count);
echo $count; //3
?>
Copy after login

执行结果如下所示:

xp***to
3
Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of php replace regular replacement method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template