PHP将单词替换为preg_replace


PHP Get the word replaced by preg_replace

如何获得preg_replace()函数替换的单词。

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

我想获取$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 );
}

这在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
// )

除了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 );

使用preg_replace不能做到这一点,但可以使用preg_place_callback:

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

notify_user替换为您要调用的通知用户的任何内容。也可以对其进行修改,以检查用户是否存在,并仅替换有效提及。