2011-09-06 75 views
0
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); 

$匹配)改变替换值,如果发现匹配返回这个数组:在preg_replace_callback在replaceContent(

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

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

此刻我preg_replace_callback函数$替换匹配值匹配[0]。我想要做的,想知道如果甚至可能的话,就是替换标签内的所有东西($ matches [2]),同时可以执行$ matches [1]检查。

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

回答

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. 如果替换字符串需要包含原始信息(例如<nlist><alist>标记中的可能属性),则还需要将这些数据存入捕获组中,以便在$matches内可用。