How to use the preg_replace() function in PHP for regular expression replacement
Regular expression is a powerful pattern matching tool. In PHP, use preg_replace The () function can implement regular expression replacement for strings. This article will introduce how to use the preg_replace() function for regular expression replacement and provide specific code examples.
The syntax of the preg_replace() function is as follows:
string preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Among them:
The following uses several practical examples to demonstrate the use of the preg_replace() function.
$str = "Today is 2022/12/31."; $newStr = preg_replace("/d+/", "#", $str); echo $newStr;
Output result:
Today is #/#/#.
$str = "My email is test@example.com."; $newStr = preg_replace("/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}/", "***@***.com", $str); echo $newStr;
Output result:
My email is ***@***.com.
$html = "<p>Hello, <b>world</b>!</p>"; $cleanHtml = preg_replace("/<[^>]*>/", "", $html); echo $cleanHtml;
Output result:
Hello, world!
It should be noted that the preg_replace() function performs pattern matching through regular expressions, so the correct writing of the pattern is crucial to the effect of replacement. . When writing regular expressions, you can use various special characters, quantifiers, selectors, etc. to build more flexible pattern matching rules.
To sum up, the preg_replace() function is a powerful function in PHP for regular expression replacement. By mastering the syntax of regular expressions and the use of the preg_replace() function, you can replace various patterns in strings.
The above is the detailed content of How to use preg_replace() function in PHP for regular expression replacement. For more information, please follow other related articles on the PHP Chinese website!