2013-12-18 51 views
-1

我有这个变量,使@每个字变成一个链接。但是现在我需要将这个值作为一个变量来创建一个函数。 很难解释,所以我会用代码展示它。

$text = preg_replace("/@([^\s]+)/", "<a href=\"profile.php?id=$1\" class=\"at\">@$1</a>", $text); 

这里是变量,我想要的是$1做成一个变量。我试图解决这个问题,但我不能解决,因为我不知道该怎么做。我怎样才能做到这一点?

在此先感谢!

+0

因此,你想获得一个名为'$ 1'包含的变量的值吗?或者你想保存'$ 1'作为这行的外部变量*吗? –

+1

我不知道你在做什么。你在寻找preg_match()吗? – Seb

+0

你的代码已经在工作。 –

回答

2
function makeALink($value) { 
    // Do something here with $value, for example make a link 
    return "<a href=\"profile.php?id=$value\" class=\"at\">@$value</a>"; 
} 

$text = preg_replace_callback("/@([^\s]+)/", "makeALink", $text); 
0

只是使用preg_match_all()而不是preg_replace。

$matches = array(); 
preg_replace_all("/@([^\s]+)/", $text, $matches); 

// $matches[0] contains the with @. $matches[1] contains your hits without the @ 
echo $matches[1][0]; // your first hit without the @ 
echo $matches[1][1]; // your second hit without the @ 
echo $matches[1][2]; // your third hit without the @