$content = file_get_contents($filename);//字符串
//正则匹配
$ary = array(  '/\<\?php([^\<\?]*?)echo(\s*)\$tag\[[\'|\"]path.root[\'|\"]\]+(.*?)\?\>/',
   '/\<\?php([^\<\?]*?)echo(\s*)\$tag\[[\'|\"]path.skin[\'|\"]\]+(.*?)\?\>/',
   '/\<\?php([^\<\?]*?)doc_article\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_download\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_focus\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_guestbook\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_jobs\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_linkers\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_list\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_mapshow\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_picture\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_poll\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_product\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)doc_video\((.*?)\)+(.*?)\?\>/e',
   '/\<\?php([^\<\?]*?)nav_sub\((.*?)\)+(.*?)\?\>/e',
   '/\<\/head\>/',
);
//替换参数
$ary2 = array( $tag['path.root'],
   $tag['path.skin'],
   'func("article","$2")',
   'func("download","$2")',
   'func("focus","$2")',
   'func("guestbook","$2")',
   'func("jobs","$2")',
   'func("linkers","$2")',
   'func("list","$2")',
   'func("mapshow","$2")',
   'func("picture","$2")',
   'func("poll","$2")',
   'func("product","$2")',
   'func("video","$2")',
   'func("nav_sub","$2")',
   $style.'</head>',    
);

$content = preg_replace($ary, $ary2, $content);

echo $content;
求助怎么将preg_replace替换成preg_replace_callback

解决方案 »

  1.   

    要使用 fun 函数的提出来,$content = file_get_contents($filename);//字符串
    //正则匹配
    $ary = array(
       '/\<\?php([^\<\?]*?)doc_([a-z]+)\((.*?)\)+(.*?)\?\>/',
       '/\<\?php([^\<\?]*?)(nav_sub)\((.*?)\)+(.*?)\?\>/',
    );$content = preg_replace_callback($ary, function($matches){  
    //$matches[2] 就是 article, download, nav_sub ....
    //$matches[3] 就是 之前的 $2
    return func($matches[2],$matches[3]);  
    }, $content);
    //不使用函数 fun 的单独替换
    $aryFind = array(  '/\<\?php([^\<\?]*?)echo(\s*)\$tag\[[\'|\"]path.root[\'|\"]\]+(.*?)\?\>/',
       '/\<\?php([^\<\?]*?)echo(\s*)\$tag\[[\'|\"]path.skin[\'|\"]\]+(.*?)\?\>/',
       '/\<\/head\>/',
    );
    $aryReplace = array( $tag['path.root'],
       $tag['path.skin'],
       $style.'</head>',    
    );
    $content = preg_replace($aryFind, $aryReplace, $content);echo $content;