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)?

2
  • Possible duplicate of Add http:// prefix to URL when missing Commented Jul 12, 2018 at 19:04
  • I wouldn't use the accepted answer in that since it only looks for http://, but the other answers look good. Commented Jul 12, 2018 at 19:05

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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 %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.