0

I'd like to make URLs inside a text output clickable without having to escape the whole output. First I wanted to do it like this, but I would have to escape all of the output which is a security risk.

function formatContent($content)
  {
    $url_filter_protocol = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    $url_filter_www = "/(www)\.[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

    if (preg_match($url_filter_protocol, $content, $url)) {
      return preg_replace($url_filter_protocol, "<a href='$url[0]' target='_blank'>$url[0]</a> ", $content);
    } elseif (preg_match($url_filter_www, $content, $url)) {
      return preg_replace($url_filter_www, "<a href='https://$url[0]' target='_blank'>$url[0]</a> ", $content);
    } else {
      return $content;
    }
  }
{!! nl2br(formatContent($post->content)) !!}

Does anybody know, how I could convert URLs in strings without having to escape to whole output?

arety_
  • 1,983
  • 2
  • 10
  • 23
  • Possible duplicate of [How do I linkify urls in a string with php?](https://stackoverflow.com/questions/507436/how-do-i-linkify-urls-in-a-string-with-php) – User863 May 24 '19 at 14:12

1 Answers1

0

One way would be to split up your original string into parts, remember which parts are links and then print the parts separately, building the link in your view.
I'm not gonna type out everything, but it would be something like this in your view:

@foreach($postArray as $postItem)
    @if($postItem['type'] == 'link') <a href="{{$postItem['content']}}">{{$postItem['content']}}</a>
    @else {{$postItem['content']}}
    @endif
@endforeach

Another way would be to use javascript/jQuery to find links and transform them afterwards, but i don't know if that is an option in your view.

MrEvers
  • 1,040
  • 1
  • 10
  • 18