如何锚定数组中的句子

I want to anchor the sentence words that are in the array.

<?php
$names = array('sara', 'max', 'alex');
foreach ($names as $dt) {
    $name = '@' . $dt;
    $text = preg_replace('/(' . $name . '\s)/', ' <a href=' . $dt . '>\1</a> ', $text);
}
echo $text;
?>

when my sentence like this it works well.

 $text = "@sara @alex @max";

but when my sentence like this

$text = "hello @sara hello @max hello @alex"; 

it doesn't work well.

Whatever the string you use, you don't reach a satisfactory outcome because:

  • a name at the end of the string isn't replaced
  • you obtain duplicate spaces around the replaced items
  • there's a trailing space at the end of the href attribute
  • you need one pass per name to proceed a single string

That's why I suggest to do all replacements in one pass and to use a negative lookahead to check if the next character is a white-space or the end of the string:

$text = "hello @sara hello @max hello @alex";

$names = array('sara', 'max', 'alex');

$pattern = '~@(' . implode('|', $names) . ')(?!\S)~';
$text = preg_replace($pattern, '<a href="$1">$0</a>', $text);

Note that you can replace (?!\S) with (?!\w) (or \b, depending of what characters are allowed in names).