在 preg_replace 中使用子字符串

Using substring within preg_replace

我有一个 preg_replace:

$text = preg_replace("/(\+?[\d-\(\)\s]{8,25}[0-9]?\d)/", "", $text);

我想在此 preg_replace 中使用两个子字符串。它应该看起来像这样:

$text = preg_replace("/(\+?[\d-\(\)\s]{8,25}[0-9]?\d)/", "<span id='number' data-last=substr(, -5)>substr(, 0, -5)<span>****<div class='showphone'>Show</div></span></span>", $text);

注意那里的两个子串。显然这不是一个有效的例子,但我想知道是否有可能让它发挥作用。有什么想法吗?

您不能像使用变量一样在双引号中使用函数。您也不能对捕获的正则表达式值使用函数,您应该使用 preg_replace_callback。像这样:

$text = preg_replace_callback("/(\+?[\d-\(\)\s]{8,25}[0-9]?\d)/", function($match) {
    return "<span id='number' data-last=" . substr($match[1], -5) . ">" . substr($match[1], 0, -5) . "<span>****<div class='showphone'>Show</div></span></span>";
}, $text);

应该这样做。虽然没有示例字符串,但我无法对此进行测试。