Home  >  Article  >  Backend Development  >  How to replace all matching strings in php

How to replace all matching strings in php

王林
王林Original
2020-09-19 15:49:233059browse

How to replace all qualified strings in php: You can use the preg_replace() function to achieve this. The preg_replace() function is used to perform a regular expression search and replacement.

How to replace all matching strings in php

php provides a function preg_replace(), which can achieve our needs very well. Let's talk about the usage of this function.

(Recommended tutorial: php video tutorial)

preg_replace function performs a regular expression search and replacement.

Full syntax:

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

Return value:

If subject is an array, preg_replace() returns an array, otherwise it returns a string.

If a match is found, the replaced subject is returned, otherwise the unchanged subject is returned. If an error occurs, NULL is returned.

Example:

<?php
$str = &#39;phpcn c   n&#39;;
$str = preg_replace(&#39;/\s+/&#39;, &#39;&#39;, $str);
echo $str;
?>

Related recommendations:php training

The above is the detailed content of How to replace all matching 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