我有一个名为 $ body 的字符串,并且我尝试替换该字符串中的用户名(如果它们存在于users表中)并用锚标记将它们包装起来,如果只有一个用户,则该代码可以正常工作在字符串中,但是如果字符串中的用户名超过一个,则如果该字符串中的用户超过一个用户,并且其中一个是真实用户,而另一个则不存在,则我的函数将特别受打击。
public function setBodyAttribute($body)
{
preg_match_all('/@([\w\-]+)/', $body, $matches);
$users = $matches[1];
foreach ($users as $user) {
if (User::where('name', $user)->exists()) {
$body = preg_replace($pattern, '<a href=/profiles/$1>$0</a>', $body);
}
}
$this->attributes['body'] = $body;
}
答案 0 :(得分:0)
尝试这样做:
$newuser = preg_replace("/@{$user}/", "<a href=/profiles/$user>@$user</a>", $body);
答案 1 :(得分:0)
preg_match('/@([\w\-]+)/', $body, $matches);
$users=User::whereIn('name',$matches[1])->pluck('name')->toArray()
foreach($users as $user) {
$body = str_replace('@'.$user, "<a href=/profiles/$user>
<strong>@$user</strong></a>", $body);
}
$this->attributes['body'] = $body;