【问题标题】:changing the replace value in preg_replace_callback更改 preg_replace_callback 中的替换值
【发布时间】:2011-11-11 01:53:15
【问题描述】:
function replaceContent($matches = array()){
    if ($matches[1] == "nlist"){
        // do stuff
        return "replace value";
    } elseif ($matches[1] == "alist"){
        // do stuff
        return "replace value";
    }

    return false;
} 

preg_replace_callback('/<([n|a]list)\b[^>]*>(.*?)<\/[n|a]list>/','replaceContent', $page_content);

如果找到匹配项,replaceContent() 中的$matches 将返回此数组:

Array
(
    [0] => <nlist>#NEWSLIST#</nlist>
    [1] => nlist
    [2] => #NEWSLIST#
)

Array
(
    [0] => <alist>#ACTIVITYLIST#</alist>
    [1] => alist
    [2] => #ACTIVITYLIST#
)

目前我的 preg_replace_callback 函数将匹配值替换为 $matches[0]。我正在尝试做的事情并想知道是否有可能替换标签 ($matches[2]) 中的所有内容,同时能够进行 $matches[1] 检查。

在这里测试我的正则表达式:http://rubular.com/r/k094nulVd5

【问题讨论】:

    标签: php regex preg-replace preg-replace-callback


    【解决方案1】:

    您可以简单地调整返回值以包含您不想原样替换的部分:

    function replaceContent($matches = array()){
        if ($matches[1] == "nlist"){
            // do stuff
            return sprintf('<%s>%s</%s>',
                           $matches[1],
                           'replace value',
                           $matches[1]);
        } elseif ($matches[1] == "alist"){
            // do stuff
            return sprintf('<%s>%s</%s>',
                           $matches[1],
                           'replace value',
                           $matches[1]);
        }
    
        return false;
    } 
    
    preg_replace_callback('/<([n|a]list)\b[^>]*>(.*?)<\/[n|a]list>/','replaceContent', $page_content);
    

    注意:

    1. sprintf 中的模式是根据用于preg_replace_callback 的正则表达式生成的。
    2. 如果替换字符串需要包含来自原始字符串的更多信息(例如,&lt;nlist&gt;&lt;alist&gt; 标记中的可能属性),您还需要将此数据放入捕获组中,以便在 @ 中可用987654326@.

    【讨论】:

      猜你喜欢
      • 2015-08-09
      • 1970-01-01
      • 2017-08-31
      • 2014-02-19
      • 2014-02-16
      • 1970-01-01
      • 2013-01-17
      • 2013-03-05
      相关资源
      最近更新 更多