Home >Backend Development >PHP Problem >Detailed introduction to the difference between preg_filter() and preg_replace() in PHP
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.
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);
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);
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!