/Laravel

Extracting tags mention and links to render in html

It’s pretty simple to extract mention and tags from raw html, it’s regular expressions implementing.


For example, we have a content is:

Lorem ipsum dolor sit amet #Yish, consectetur adipiscing elit. Nunc pharetra tortor a dui pellentesque, eget mattis turpis laoreet. Maecenas consequat maximus aliquam. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean sodales diam et turpis gravida facilisis. Duis sed sem quam. Pellentesque ornare, turpis vitae consectetur sodales, orci sapien venenatis leo, non porttitor mauris dolor id sapien. <https://google.com> Aliquam dignissim lectus nulla, ut ornare nisl volutpat eget. Pellentesque augue nibh, bibendum non condimentum in, porta id tortor. Curabitur mattis justo vitae nulla facilisis #gravida. Quisque feugiat eget arcu vitae commodo. Interdum et malesuada fames ac ante ipsum primis in faucibus.
    
<https://laravel.com>

# hello
# world
# this-is

Firstly, you do the parser method.

class Editor
{
	public static function toHtml($raw)
	{
		// fetching danger label
		$content = e($raw);
		// fetching links, if you do tag fetching on first, you will went wrong.(anchor will be transfer)
		$content = preg_replace_callback(
			'/(https?:\\/\\/\\S+)|([a-z]+\\.[a-z]+(?:\\/\\S+)?)/'
			, function($matches) {
			$protocol = starts_with($matches[0], ['https', 'http']);
			$link = $protocol ? $matches[0] : "//$matches[0]";
			return "<a target=\\"_blank\\" href=\\"{$link}\\" class=\\"bear\\">$matches[0]</a>";
		}, $content);
		$content = preg_replace([
			'/[^\\S]#([\\w-]\\w+)/',
			'/@([\\w-]\\w+)/',
		], [
			'<a href="/tags/$1">$0</a>',
			'<a href="/$1">$0</a>',
		], $content);
		return nl2br($content);
	}

	public function origin($raw, $mode = true)
	{
		return $mode ? nl2br($raw) : $raw;
	}
}

And you can set a singlton and facade to use it, it’s very simple.

//Service Provider
$this->app->singleton('editor', function($app) {
	return new Editor;
});
//Facade
protected static function getFacadeAccessor()
{
	return 'editor';
}

Finally, you can use in blade

{!! Editor::toHtml($post->content) !!}
Yish

Yish

The creator of yish.dev

Read More