Home > Backend Development > PHP Problem > Detailed introduction to the difference between preg_filter() and preg_replace() in PHP

Detailed introduction to the difference between preg_filter() and preg_replace() in PHP

醉折花枝作酒筹
Release: 2023-03-11 08:50:01
forward
2306 people have browsed it

In PHP, we know that there are two regular expression filter functions, namely preg_filter() and preg_replace(), but not everyone knows the difference between them. Today I will take you to find out more about it.

Detailed introduction to the difference between preg_filter() and preg_replace() in PHP

PHP regular replacement filter function

How to say? The regular replacement filter function is very similar to the replacement function we talked about before, with only a little difference. I don’t know if you have noticed it!!

==preg_filter()==Function: Perform a regular expression search and replacement

Usually the preg_filter() function is equivalent to the preg_replace() function

The code of case 1 is as follows:

$arr=array('1.jpg','2.txt','3.doc','4.exe','5.php');
$pattern='/\.jpg|\.txt/';$replacement='';
$result1=preg_replace($pattern, $replacement, $arr);
$result2=preg_filter($pattern, $replacement, $arr);
show($result2);
Copy after login

The actual difference between preg_filter() and preg_replace()

The code of case 2 is as follows:

$pattern=array(
    "/\d+/",
    "/ccc/");
$replacement=array(
    '1024',
    'PHP');
$string=array(
    '1234aaa',
    'abbbccc',
    'wampserver');
  $result1=preg_replace($pattern, $replacement, $string);
  show($result1);
  $result2=preg_filter($pattern, $replacement, $string);
  show($result2);
Copy after login

So the difference is as follows:

preg_filter() will only return the array elements that have been replaced and filtered, and the array elements that have not been replaced are not returned.

preg_replace() returns not only the array elements that have been replaced and filtered, but also Elements that have not been replaced will also be retained and returned!

In fact, as long as everyone tests and prints out each other's results, you can immediately know the difference between them!

Recommended learning:php video tutorial

The above is the detailed content of Detailed introduction to the difference between preg_filter() and preg_replace() in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:imooc.com
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