バックエンドとフロントエンドを行き来するWEBプログラマ―のメモ帳

WEBプログラマ―。バックエンドはPHP, MySQL, CentOS系, フロントエンドはJavaScript, jQuery, HTML, CSSで仕事してます。

Laravelで、テキスト内のhttpリンクの変換方法

Laravelにて、プロフィールなどの説明に、httpのリンクを途中で入れてあった場合、ちゃんとリンクされるようにしたい

こんな感じにしたい場合

理想はこの状態です。ちょっとハマってしまったため、メモします。
f:id:mashiro_ruka:20190704140707p:plain
使用アイコン:なゆみ様

このようなプロフィールになっているとします。
f:id:mashiro_ruka:20190704135901p:plain

間違った方法

Controllerで

<?php
~略~
'introduction' => $user->introduction

blade.php

<p>
 {{ $introduction }}
</p>

これだと、このようになってしまいます。
f:id:mashiro_ruka:20190704135911p:plain

解決方法

まずは、httpにaタグをつけます。
app/Libsフォルダに、PlanetextToUrl.phpを追加して以下の内容にします。

<?php

namespace App\Libs;

class PlanetextToUrl
{
    public static function convertLink($plane_text)
    {
        //URL抽出の正規表現
        $pattern = '/https?:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:@&=+$,%#]+/';

        //該当する文字列に処理
        $convert_text = preg_replace_callback($pattern,function ($matches) {

            return '<a href="'.$matches[0].'">'.$matches[0].'</a>';
        },htmlspecialchars($plane_text));

        return $convert_text;
    }
}

Controller内

<?php
//プロフィール紹介を文字列の中にurlがあったらコンバートするようにします。
$introduction = PlanetextToUrl::convertLink($user->introduction);

//出力します。 
'introduction' => $introduction

blade.php内では、以下のように改行させつつ、エスケープさせないように{!! $変数 !!}と記述します。
※nl2brで囲って、元のテキストと同じように、改行させます。

<p>
{!! nl2br($introduction) !!}
</p>

f:id:mashiro_ruka:20190704140707p:plain
これで、うまくいきました!

参考サイト

befool.co.jp

leben.mobi

お借りした素材サイト

www.ac-illust.com