Home  >  Article  >  Backend Development  >  How to use regex to replace strings in php

How to use regex to replace strings in php

青灯夜游
青灯夜游Original
2021-11-30 18:51:063702browse

php正则替换字符串的方法:1、使用preg_replace()函数,语法“preg_replace(正则表达式,替换值,字符串)”;2、使用preg_filter()函数,语法“preg_filter(正则表达式,替换值,字符串)”。

How to use regex to replace strings in php

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

php利用正则来替换字符串的两种方法:

  • preg_replace() 

  • preg_filter()

preg_replace() 和preg_filter()函数都可以执行正则表达式的搜索和替换,不同的是 preg_filter() 函数只返回匹配成功的结果,而 preg_replace() 返回所有结果,不管是否匹配成功。

preg_replace() 和preg_filter()函数的语法类似:

preg_replace($pattern, $replacement, $subject [, $limit = -1 [, &$count]])
preg_filter($pattern, $replacement, $subject [, $limit = -1 [, &$count]])

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

参数说明如下:

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

  • $replacement:用于替换的字符串或字符串数组。如果这个参数是一个字符串,并且 $pattern 是一个数组,那么所有的模式都使用这个字符串进行替换。如果 $pattern 和 $replacement 都是数组,每个 $pattern 使用 $replacement 中对应的元素进行替换。如果 $replacement 中的元素比 $pattern 中的少,多出来的 $pattern 使用空字符串进行替换。

  • $subject:要进行搜索和替换的字符串或字符串数组,如果 $subject 是一个数组,搜索和替换回在 $subject 的每一个元素上进行, 并且返回值也会是一个数组。

  • $limit:可选参数,每个模式在每个 $subject 上进行替换的最大次数。默认是 -1(无限)。

  • $count:可选参数,如果指定,将会被填充为完成的替换次数。

示例:

preg_filter()和preg_replace()利用正则来替换字符串

How to use regex to replace strings in php

推荐学习:《PHP视频教程

The above is the detailed content of How to use regex to replace strings in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:What is apache in phpNext article:What is apache in php