Home > Blockchain >  Auto hyperlinks inside article using given tags - Laravel
Auto hyperlinks inside article using given tags - Laravel

Time:05-31

I am developing an article website, I have a list of 5-10 tags attached with each article.

Thing I am trying to achieve is if there is same exact word (from given tags) is used in article, it should hyperlinks to that tag/category.

For example tags are as following:

trading, financial, growth, imports, government

And article is like:

Government has put sanctions on imports from northern allies to stabilize its economy. This will support growth of GDP.

So according to my requirements government, imports & growth should be hyperlinked with abc.com/tags/imports.

How can I achieve this using laravel blade. Is their any package for that? I couldn't find any.

CodePudding user response:

It makes sense to put the links to the article before you pass it to blade. After you've pulled the data from database you can handle it with some method based on str_replace (or str_ireplace for case-insensitive) like this:

public function addTagLinks(string $text, array $tags): string
{
  $links = [];
  foreach($tags as $tag) {
    $links[] = '<a href=' .url(...) . '>'.$tag.'</a>';
  }
  return str_replace($tags, $links, $text);
}
  • Related