How to use regular expressions to replace Chinese characters in PHP?

Guanhui
Release: 2023-03-02 22:40:02
Original
3099 people have browsed it

How to use regular expressions to replace Chinese characters in PHP?

PHP如何使用正则替换中文?

在PHP中可以使用函数“preg_replace()”进行正则替换,其匹配中文的正则为“/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u”,使用时只需将正则、替换字符、字符串依次传入即可。

preg_replace 函数语法

preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed
Copy after login

使用示例

<?php
$string = &#39;The quick brown fox jumps over the lazy dog.&#39;;
$patterns = array();
$patterns[0] = &#39;/quick/&#39;;
$patterns[1] = &#39;/brown/&#39;;
$patterns[2] = &#39;/fox/&#39;;
$replacements = array();
$replacements[2] = &#39;bear&#39;;
$replacements[1] = &#39;black&#39;;
$replacements[0] = &#39;slow&#39;;
echo preg_replace($patterns, $replacements, $string);
?>
Copy after login
<?php
$string = &#39;April 15, 2003&#39;;
$pattern = &#39;/(\w+) (\d+), (\d+)/i&#39;;
$replacement = &#39;${1}1,$3&#39;;
echo preg_replace($pattern, $replacement, $string);
?>
Copy after login

推荐教程:《PHP

The above is the detailed content of How to use regular expressions to replace Chinese characters in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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