所以,我有一个 preg_replace 函数,它应该替换以下模式: 用户名前面带有 @ 字符。
我在名为 allMembers() 的多维数组中获取了用户名,并使用正则表达式将任何单词替换为 @ 字符及其周围的空格:
/\B@[a-z-]+\s/
但是如何通过 preg_replace 函数运行数组中包含的用户名呢?因此,只需一种替代多种模式。
$mentionPattern = "/\B@[ USERNAMES FROM ARRAY ALLMEMBERS HERE ]+\s/";
$mentionReplace = "<a class='userMention'>$0</a>";
preg_replace($mentionPattern, $mentionReplace, $text);
示例:
我网站上的用户:John、Harry、Peter
每当有人添加像“bla bla @John bla bla”这样的消息时,“@John”部分应该被其他内容替换。因此,替换取决于 @ 和现有用户名(我在数组内)的使用。
最佳答案
一个好方法是使用 preg_replace_callback。优点是您可以避免使用缓慢交替的模式(特别是如果您有很多用户):
$result = preg_replace_callback('~@(\w+)~', function ($m) use ($usernames) {
return (in_array($usernames, $m[1])) ? '<a ...>' . $m[0] . '</a>'
: $m[0];
}, $text);
关于php - 如何在 preg_replace 中使用数组和正则表达式作为模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264047/