简体   繁体   中英

How do I add the http protocol to a link?

This should be basic knowledge, but somehow it eludes me. It has been working fine up till now, but for some reason my code no longer adds the http protocol...

I have $model->www which contains www.some-page.no (plain text).

Up till now I've been outputting this as follows:

<a href="<?= $model->www; ?>> Click me </a>

Expected output should be http://www.some-page.no
but now I get http://my-local-machine.com/page/a/http://www.some-page.no

If I do <a href="http://<?= $model->www; ?>> Click me </a> it works fine. The problem is that I don't know if the URL already contains http:// .

Is there a Yii way or a PHP way of adding http protocol if the link does not have it? Or do I have to custom make a function that checks for the string http:// ?

The link is properly sanitized. So there is no need for htmlspecialchars or similar functions.

You can do this with parse_url

$url = 'www.google.be';
if (parse_url($url, PHP_URL_SCHEME) === null) $url = 'http://'.$url;

Just use str_replace :

<a href="http://<?php str_replace('http://', '', $model->www); ?>" Click me</a>

UPDATE: If you are also concerned about other protocols (see DarkBee's comment):

<a href="http://<?php str_replace(array('http://', 'https://', 'ftp://'), '', $model->www); ?>" Click me</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM