2015-02-10 114 views
0

如何通过preg_replace()函数获取替换的单词。PHP获取由preg_replace替换的单词

preg_replace('/[@]+([A-Za-z0-9-_]+)/', '<a href="/$1" target="_blank">$0</a>', $post); 

我想获得$1变量,以便我可以进一步使用它。

+0

不理解你的问题。你能举个例子吗? – 2015-02-10 11:47:21

+0

当某人在他的帖子中提到(使用类似@hammad的用户)时,我通过使用问题中的代码将提及转换为链接。但问题是我想让提到的用户注意到他被提及,所以我想要那个被替换的**用户名**。希望你明白! – 2015-02-10 11:52:45

+0

在preg_match_all中使用'[@] +([A-Za-z0-9 -_] +)'正则表达式。并从索引1获取所需的字符串。 – 2015-02-10 11:57:57

回答

1

捕捉它,你替换表达式之前:

// This is where the match will be kept 
$matches = array(); 
$pattern = '/[@]+([A-Za-z0-9-_]+)/'; 

// Check if there are matches and capture the user (first group) 
if (preg_match($pattern, $post, $matches)) { 
    // First match is the user 
    $user = $matches[1]; 

    // Do the replace 
    preg_replace($pattern, '<a href="/$1" target="_blank">$0</a>', $post); 
} 
+0

匹配是否包含@符号? – 2015-02-10 12:02:27

+0

不,它不会,它将包含第一个圆括号内的字符 - ([A-Za-z0-9 -_] +) – nXu 2015-02-10 12:10:48

0

您应该使用的preg_match除的preg_replace。 preg_replace仅用于替换。

$regex = '/[@]+([A-Za-z0-9-_]+)/'; 
preg_match($regex, $post, $matches); 
preg_replace($regex, '<a href="/$1" target="_blank">$0</a>', $post); 
0

你不能这样做,与preg_replace函数,但是你可以用preg_replace_callback做到这一点:

preg_replace_callback($regex, function($matches){ 
notify_user($matches[1]); 
return "<a href='/$matches[1]' target='_blank'>$matches[0]</a>"; 
}, $post); 

取代notify_user,不管你会打电话通知用户。 也可以修改它以检查用户是否存在并仅替换有效的提及。

0

这是不可能与preg_replace(),因为它返回完成的字符串/数组,但不保留替换的短语。您可以使用preg_replace_callback()手动实现此目的。

$pattern = '/[@]+([A-Za-z0-9-_]+)/'; 
$subject = '@jurgemaister foo @hynner'; 
$tokens = array(); 

$result = preg_replace_callback(
       $pattern, 
       function($matches) use(&$tokens) { 
        $tokens[] = $matches[1]; 
        return '<a href="/'.$matches[1].'" target="_blank">'.$matches[0].'</a>'; 
       }, 
       $subject 
     ); 

echo $result; 
// <a href="/jurgemaister" target="_blank">@jurgemaister</a> foo <a href="/hynner" target="_blank">@hynner</a> 
print_r($tokens); 
// Array 
// (
// [0] => jurgemaister 
// [1] => hynner 
//) 
+0

-1全局(可以用use替换(&$ token)只有在$主题 – hynner 2015-02-10 12:19:03

+0

中只有一个提到时才会起作用 – jurgemaister 2015-02-10 12:21:38

+0

还有一个问题,即它无法正常工作多次提及 – hynner 2015-02-10 12:36:10