-1

I have the following strings having pattern which given below:

1)click on http://www.google.com

2) click onhttp://www.google.com".

3) click on www.google.com

4) click onwww.google.com

5) click on www.google.com#xyz

6) click onwww.google.com#xyz

I need to convert all these string to below manner with using of regular expression:

click on <a href="http://www.google.com" target="_blank">http://www.google.com</a>

click onhttp://www.google.com

click on <a href="http://www.google.com" target="_blank">www.google.com</a>

click onwww.google.com

click on <a href="http://www.google.com#xyz" target="_blank">www.google.com#xyz</a>

click onwww.google.com
Abhishek Kasera
  • 240
  • 1
  • 12

3 Answers3

0
function linkify( $string ) {
    return preg_replace( "~\bhttp(s)?://[^<>[:space:]]+[[:alnum:]/]\b~", "<a href=\"\\0\" target=\"_blank\">\\0</a>", $string);
}

https://eval.in/218437

Valentin Rodygin
  • 864
  • 5
  • 12
-2

You could use something like;

/\s((http(s)?\:\/\/[a-zA-Z0-9\-\.]+\.)(com|org|net|mil|edu|))/i

With a replace of

<a href="$2">$2<a/>

http://regex101.com/r/nI4gU6/7

Which would make your PHP something like;

 $str = preg_replace(
            '/\s((http(s)?\:\/\/[a-zA-Z0-9\-\.]+\.)(com|org|net|mil|edu))/i',
            ' <a href="${1}" target="_blank">${1}</a>', 
             $s);

For example: https://eval.in/218269

(Note: You'd need to modify it to allow all the other (g)TLD's - however the basic set-up is there)

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
-3

You could have something like this:

<?php
 function addhttp($url) {
   if (false === strpos($url, '://')) {
      $url = 'http://' . $url;
   }
   return $url;
 }

 $url = "www.google.com";

 var_dump(addhttp($url)); 
 ?>

Then for the URLS where you want to output "http://" you just pass it to the function.

Output: http://codepad.org/MlvXWRR2

Phorce
  • 4,424
  • 13
  • 57
  • 107