如何锚定数组中的句子单词

how to anchor the sentence words that are in the array too

我想锚定数组中的句子单词。

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

当我这样的句子时,效果很好。

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

但是当我这样说的时候

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

效果不佳。

无论您使用什么字符串,您都无法获得令人满意的结果,因为:

  • 字符串末尾的名称未被替换
  • 您在替换的项目周围获得了重复的 spaces
  • href 属性末尾有一个尾随 space
  • 每个名字需要通过一次才能处理一个字符串

这就是为什么我建议一次性完成所有替换,并使用否定前瞻来检查下一个字符是白色-space还是字符串结尾:

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

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

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

请注意,您可以将 (?!\S) 替换为 (?!\w)(或 \b,具体取决于名称中允许的字符)。