在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
使用示例
<?php$string = 'the quick brown fox jumps over the lazy dog.';$patterns = array();$patterns[0] = '/quick/';$patterns[1] = '/brown/';$patterns[2] = '/fox/';$replacements = array();$replacements[2] = 'bear';$replacements[1] = 'black';$replacements[0] = 'slow';echo preg_replace($patterns, $replacements, $string);?>
<?php$string = 'april 15, 2003';$pattern = '/(\w+) (\d+), (\d+)/i';$replacement = '${1}1,$3';echo preg_replace($pattern, $replacement, $string);?>
推荐教程:《php》
以上就是php如何使用正则替换中文?的详细内容。
