Perform a regular expression search and replace using a callback
<?php
function preg_replace_callback(
array|string $pattern,
callable $callback,
array|string $subject,
int $limit = -1,
&$count,
int $flags = 0
): array|string|null { }
@param string|string[] $pattern
@param callable $callback
@param string|string[] $subject
说明
$callback()接受一个参数$matches
$matches[0]是$subject中符合$pattern匹配的部分
$matched[1]是$pattern中第1个捕获的部分
...
$matched[k]是$pattern中第k个捕获的部分
实际使用
$aa = perg_replace_callback('~&#([0-9]+);~', function($matches){
return chr($matches[1]);
}, 'It's');
echo $aa; # "It's"
- chr用于将数字转换为ASCII码
- '~'用于界定正则表达式
- &#[0-9]+;用来匹配带有数字的html实体编码,将其中的数字捕获以后,可以转换为对应的ASCII码,恢复成人类能看懂的字符