【问题标题】:Using substring within preg_replace [duplicate]在 preg_replace 中使用子字符串 [重复]
【发布时间】:2019-08-05 18:12:23
【问题描述】:

我有一个 preg_replace:

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

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

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

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

【问题讨论】:

    标签: php substring preg-replace


    【解决方案1】:

    您不能像使用变量一样在双引号中使用函数。您也不能在捕获的正则表达式值上使用函数,您应该使用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);
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 2012-04-16
      • 2014-05-09
      • 1970-01-01
      • 2020-02-24
      • 2011-09-28
      • 2013-12-04
      相关资源
      最近更新 更多