I want to link all tags inside content variable, I can achieve it with foreach, but if one tag is `car wash` and another is `car` it's creating link inside link, how to avoid that ?

My code:

```
$tags = Tag::all();

foreach ($tags as $tag) {
    if(stripos($content, $tag->name) !== false) {
        $content = str_ireplace($tag->name, '<a href="' . route('tag.show', [$tag->id, slug($tag->name)]) . '" target="_blank">' . $tag->name . '</a>', $content);
    }
}

```

One of the solutions would be sorting tags by length, from small to larg, but nah, I need a better solution

EDIT: Storing already matched tags in a new array and checking with foreach and strpos if they contain substring before replacing, will be a solution for that, but another issue, strpost ans str\_replace will match partial words like, if tag is car and content contains caring, there will be a partial match and it will also get replaced, how to avoid partial match ?

EDIT 2: Thanks @Kinglish for help, final code:

```
$tags = Tag::orderByRaw('CHAR_LENGTH(name) DESC')->get();

$linkedTags = [];
foreach ($tags as $tag) {
    foreach ($linkedTags as $linkedTag) {
        if(stripos($linkedTag, $tag->name) !== false) {
            continue 2;
        }
    }

    if(stripos($content, $tag->name) !== false) {

        $pos = stripos($content, $tag->name);
        $disallowedCharacters = [
            '-',
            '/',
            '@',
            '\\',
            '#',
            '*',
            '&'
        ];

        if ($pos != 0) {
            $charBefore = substr($content, $pos -1, 1);
            if (ctype_alpha($charBefore) || ctype_digit($charBefore) || in_array($charBefore, $disallowedCharacters)) {
                continue;
            }
        }

        $charAfter = substr($content, $pos + strlen($tag->name), 1);
        if (ctype_alpha($charAfter) || ctype_digit($charAfter) || in_array($charAfter, $disallowedCharacters)) {
            continue;
        }

        $linkedTags[] = $tag->name;
        $content = str_ireplace($tag->name, '<a href="' . route('tag.show', [$tag->id, slug($tag->name)]) . '" target="_blank">' . $tag->name . '</a>', $content);
    }
}

```