mercredi 6 mai 2020

find in string and replace

I have a string called $body and I'm trying to replace usernames in that string if they exist in users table and wrap them with anchor tag, the code works fine if only one user is in the string but if more than a username in the string my function blows specially if more than a user in the string and one is a real user exists in users table and another doesn't.

foreach ($users as $user) {
        if (User::where('name', $user)->exists()){
            $newuser = preg_replace('/@([\w\-]+)/', "<a href=/profiles/$user>@$user</a>", $body);
        }else {
            $newuser  = $body;
        }
    }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire