PHP获取preg_replace替换的单词

时间:2015-02-10 11:42:31

标签: php regex

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

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

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

4 个答案:

答案 0 :(得分: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 );
}

答案 1 :(得分:0)

除了preg_replace之外,你应该使用preg_match。 preg_replace只是用于替换。

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

答案 2 :(得分: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替换为您要求通知用户的任何内容。 这也可以修改以检查用户是否存在并仅替换有效的提及。

答案 3 :(得分: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
// )