PHP Chinese regular matching and replacement examples
Regular expressions are widely used in string matching and replacement operations in PHP, which can achieve high efficiency for Chinese text deal with. This article will introduce through examples how to use Chinese regular expressions for matching and replacement in PHP.
In PHP, when using regular expressions to match and replace, the preg_match()
function is usually used for matching, preg_replace ()
function is used for replacement. Some common syntax in regular expressions:
: matches any character
: matches the previous character 0 times or Multiple times
: Match the previous character at least 1 time
: Match the previous character 0 or 1 times
: Matches any character within square brackets
: Captures the matching subpattern
: Match numbers
: Match word characters
: Match blank characters
$content = "这是一个包含中文字符的字符串"; preg_match_all('/[x{4e00}-x{9fa5}]+/u', $content, $matches); print_r($matches[0]);
/[x{4e00}-x{9fa5}] /u means matching all Chinese characters. After execution,
print_r($matches[0]) will output all matched Chinese characters.
preg_replace() function. The sample code is as follows:
$content = "这是一个包含中文字符的字符串"; $newContent = preg_replace('/[x{4e00}-x{9fa5}]+/u', '*', $content); echo $newContent;
preg_replace('/[x{4e00}-x{9fa5}] /u', '*', $content) will All Chinese characters are replaced with
*, and the replaced string is finally output.
$content = "这是一个包含标点符号的句子,你的手机号码是13612345678。"; $cleanedContent = preg_replace('/[[:punct:]]/', '', $content); preg_match('/1[3456789]d{9}/', $cleanedContent, $matches); echo $matches[0];
preg_replace(), and then matches the mobile phone number through
preg_match() and output.
The above is the detailed content of PHP Chinese regular matching and replacement examples. For more information, please follow other related articles on the PHP Chinese website!