2012-07-09 102 views
0
function anchor($text) 
{ 
return preg_replace('#\&gt;\&gt;([0-9]+)#','<span class=anchor><a href="#$1">>>$1</a></span>', $text); 
} 

这段代码用于渲染页面定位点。 我需要使用如何使用preg_replace模式的一部分作为变量?

([0-9]+) 

部分作为一个变量做一些数学定义为href标记的确切地址。 谢谢。

+0

不要使用的preg_replace然后。使用preg_match并对结果执行一些操作。 – sberry 2012-07-09 03:35:25

+0

['preg_replace_callback'](http://de.php.net/preg_replace_callback)是你的朋友。 – ccKep 2012-07-09 03:49:53

回答

1

改为使用preg_replace_callback。

在PHP 5.3 +:

$matches = array(); 
$text = preg_replace_callback(
    $pattern, 
    function($match) use (&$matches){ 
    $matches[] = $match[1]; 
    return '<span class=anchor><a href="#$1">'.$match[1].'</span>'; 
    } 
); 

在PHP 5.3 <:

global $matches; 
$matches = array(); 
$text = preg_replace_callback(
    $pattern, 
    create_function('$match','global $matches; $matches[] = $match[1]; return \'<span class=anchor><a href="#$1">\'.$match[1].\'</span>\';') 
); 
相关问题