How to use regular expressions in php to match a certain character and delete it

青灯夜游
Release: 2023-03-16 09:00:01
Original
2719 people have browsed 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)".

How to use regular expressions in php to match a certain character and delete it

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = &#39;1132hell0 2313&#39;;
$pattern = &#39;/l/i&#39;;
$replacement = &#39;&#39;;
echo preg_replace($pattern, $replacement, $str);
?>
Copy after login

How to use regular expressions in php to match a certain character and delete it

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(&#39;content-type:text/html;charset=utf-8&#39;);   
$str = &#39;1132hell0 2313&#39;;
echo "原字符串:".$str."<br>";
$pattern = &#39;/3/i&#39;;
$replacement = &#39;&#39;;
echo "处理后:".preg_filter($pattern, $replacement, $str);
?>
Copy after login

How to use regular expressions in php to match a certain character and delete it

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!

Related labels:
source:php.cn
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