Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: remove `http://` from link title

Tags:

html

string

php

I have a string that looks like:

$string = '<a href="http://google.com">http://google.com</a>';

How can I remove the http:// part from the link text, but leave it in the href attribute?

like image 653
Alex Avatar asked Feb 02 '11 13:02

Alex


People also ask

How to Remove http from URL in PHP?

Remove http://, www., and slashes from the URL First is trim() function, use for remove all slash from the URL. Second is preg_match() function, check http:// or https:// existed in URL. If yes then no need to http:// prepend otherwise you have to http:// prepend to URL. Third is parse_url() function, to parse the URL.

How to Remove http from URL?

To remove http:// or https:// from a url, call the replace() method with the following regular expression - /^https?:\/\// and an empty string as parameters. The replace method will return a new string, where the http:// part is removed.


4 Answers

Without using a full blown parser, this may do the trick for most situations...

$str = '<a href="http://google.com">http://google.com</a>';

$regex = '/(?<!href=["\'])http:\/\//';

$str = preg_replace($regex, '', $str);

var_dump($str); // string(42) "<a href="http://google.com">google.com</a>"

It uses a negative lookbehind to make sure there is no href=" or href=' preceding it.

See it on IDEone.

It also takes into account people who delimit their attribute values with '.

like image 169
alex Avatar answered Sep 19 '22 15:09

alex


$string = '<a href="http://google.com">http://google.com</a>'; 
$var = str_replace('>http://','>',$string); 

Just tried this in IDEone.com and it has the desired effect.

like image 33
Neil Knight Avatar answered Sep 17 '22 15:09

Neil Knight


In this simple case, the preg_replace function will probably work. For more stability, try using DOMDocument:

$string = '<a href="http://google.com">http://google.com</a>';
$dom = new DOMDocument;
$dom->loadXML($string);

$link = $dom->firstChild;
$link->nodeValue = str_replace('http://', '', $link->nodeValue);
$string = $dom->saveXML($link);
like image 28
lonesomeday Avatar answered Sep 18 '22 15:09

lonesomeday


$str = 'http://www.google.com';
$str = preg_replace('#^https?://#', '', $str);
echo $str; // www.google.com

that will work for both http:// and https://

running live code

like image 43
Muhammad Tahir Avatar answered Sep 20 '22 15:09

Muhammad Tahir