Home > Article > Backend Development > How to use regular expressions in php to match a certain character and delete it
Two methods: 1. Use preg_replace() to replace the matching characters with empty characters, the syntax is "preg_replace('/specified character/i','',$str)". 2. Use preg_filter(), the syntax is "preg_filter('/character/i','',$str)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php uses regular matching Two methods to delete a certain character
Method 1: Use preg_replace() for regular replacement
preg_replace() function can perform regular replacement Expression search and replacement
You only need to use preg_replace() to perform a regular expression search for the specified character and replace it with a null character.
<?php header('content-type:text/html;charset=utf-8'); $str = '1132hell0 2313'; $pattern = '/l/i'; $replacement = ''; echo preg_replace($pattern, $replacement, $str); ?>
Method 2: Use preg_filter() for regular replacement
preg_filter() is the same as preg_replace() and can be executed Regular expression search and replace.
Just execute a regular expression to search for the specified characters and replace them with null characters.
<?php header('content-type:text/html;charset=utf-8'); $str = '1132hell0 2313'; echo "原字符串:".$str."<br>"; $pattern = '/3/i'; $replacement = ''; echo "处理后:".preg_filter($pattern, $replacement, $str); ?>
Explanation: The difference between preg_replace() and preg_filter()
preg_filter() function only returns the result of successful matching. And preg_replace() returns all results, regardless of whether the match is successful.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to use regular expressions in php to match a certain character and delete it. For more information, please follow other related articles on the PHP Chinese website!