0

I have this a tag

<a href="{{ $organization->website }}">Link</a>

If $organization->website is a url that contains http:// or https:// at the start, the link will work.

However, if it doesn't, the link will bring me to something like this

http://localhost/public/www.google.com instead of www.google.com

I know that you can use // so that links without http will work, like this

<a href="//{{ $organization->website }}">Link</a>

However, links with http:// or https:// at the start will now not work instead.

Is there a solution that can work with both (URLs with no http and URLs with http)?

Jason
  • 161
  • 2
  • 5
  • 14
  • Possible duplicate of [Add http:// prefix to URL when missing](https://stackoverflow.com/questions/6240414/add-http-prefix-to-url-when-missing) – Devon Bessemer Jul 12 '18 at 19:04
  • I wouldn't use the accepted answer in that since it only looks for http://, but the other answers look good. – Devon Bessemer Jul 12 '18 at 19:05

2 Answers2

0

You can replace https://, http:// or / by just // which would do what you

like:

'//' . (strpos($url, '//') !== false ? substr($url, strpos($url, '//') + 2) : ltrim($url, '/'))

therefore it would be:

<a href="{{ '//' . (strpos($organization->website, '//') !== false ? substr($organization->website, strpos($organization->website, '//') + 2) : ltrim($organization->website, '/')) }}">Link</a>

https://www.google.com, http://www.google.com, //www.google.com, /www.google.com or www.google.com will be converted to //www.google.com which I believe is what you need

jvicab
  • 266
  • 1
  • 3
0

Here is how I solved it in twig templating, using OctoberCMS (laravel):

eventen.about_url|slice(0, 4) looks for 'http' in the beginning of the url variable, if its there it uses that link as it is, if not, it adds // before the link.

{% if eventen.about_url|slice(0, 4)=='http' %}
    <a href="{{eventen.about_url}}" target="_blank">
       Link
     </a>
{% else %}
    <a href="//{{eventen.about_url}}" target="_blank">
       Link
    </a>
{% endif %}
Terje Nesthus
  • 810
  • 3
  • 12
  • 30