1

I need help with replacing the links to the format 'http://www.link.com'

ex: from

    $output_string = 'fix me <a href="www.link.com">link</a> or fix me <a href="link.com">link</a> and fix me too <a href="http://link.com">link</a> and replace me with <a href="http://www.link.com>link</a>';

to

    $output_string = 'fix me <a href="http://www.link.com">link</a> or fix me <a href="http://www.link.com">link</a> and fix me too <a href="http://www.link.com">link</a> and replace me with <a href="http://www.link.com>link</a>';
XoR
  • 132
  • 1
  • 1
  • 10

3 Answers3

1

You may not want to rewrite http://anylinks.com to http://www.anylinks.com as some domains don't work with the www prefix.

HamZa
  • 14,671
  • 11
  • 54
  • 75
Glitch Desire
  • 14,632
  • 7
  • 43
  • 55
  • 1
    i happened to come across a website, where its www version was a completely other site. i just want to say that www.example.com != example.com and of course the same applies for the protocol. – Sharky Jun 04 '13 at 13:04
  • 1
    That's what I was getting at @Sharky, also some sites won't have `www` active because they'll instantly direct to SSL which may only be valid without the subdomain. – Glitch Desire Jun 04 '13 at 13:04
1

You can use str_replace function to achieve this

$str = 'fix me <a href="www.link.com">link</a> or fix me <a href="link.com">link</a> and fix me too <a href="http://link.com">link</a> and replace me with <a href="http://www.link.com>link</a>';
echo str_replace('www.www', 'www', str_replace('http://www.http://', 'http://www.', str_replace('a href="', 'a href="http://www.', $str)));

This will output

'fix me <a href="http://www.link.com">link</a> or fix me <a href="http://www.link.com">link</a> and fix me too <a href="http://www.link.com">link</a> and replace me with <a href="http://www.link.com>link</a>'

Live Demo

Fabio
  • 23,183
  • 12
  • 55
  • 64
  • I think a better approach is the case-insensitive version of this function - [str_ireplace](http://php.net/manual/en/function.str-ireplace.php). – Dzhuneyt Jun 04 '13 at 13:02
  • i think the better approach will be a regex, anyhow you need to change the replace of www.www => www to www.www. => www. because it will fail if the website starts with h t t p : / /www and www is part of the name (example here http://3v4l.org/hHKeK) h t t p : / / wwwoooohoooo.com – Sharky Jun 04 '13 at 13:16
0
$output_string = preg_replace('/(href=\")(http:\/\/)?/i', '$1http://', $output_string);

This regexp will find href tags in string and adds http:// if its not already there. Better then searching for 'www' since the URL might not start with www. It's not case-sensitive.

Bence Gacsályi
  • 296
  • 2
  • 4