Laravelで、テキスト内のhttpリンクの変換方法
Laravelにて、プロフィールなどの説明に、httpのリンクを途中で入れてあった場合、ちゃんとリンクされるようにしたい
間違った方法
Controllerで
<?php ~略~ 'introduction' => $user->introduction
blade.phpで
<p> {{ $introduction }} </p>
これだと、このようになってしまいます。
解決方法
まずは、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>
これで、うまくいきました!