1

Possible Duplicate:
How do I auto convert an url into a hyper link in PHP?

Let's say, I have an textfield on my website, where the user can enter anything he wants to. If the user enters a url, I would like to add code to this url in the background. Therefor I would need logic in order to recognize the url.

Example The user enters a text:

Please visit me at my website: http://www.mywebsite.org

I would like to change the code in the background to something like this:

Please visit me at my website: <a href="http://www.companywebsite.com/redirect.php?http://www.mywebsite.org">http://www.mywebsite.org</a>

How is it possible to change that link after the text has been submitted?

Community
  • 1
  • 1
Daniel
  • 1,179
  • 4
  • 18
  • 31

3 Answers3

2
<?php

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links
       echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);

} else {

       // if no urls in the text just return the text
       echo $text;

}
?>
0

If you're saving user input and displaying it on the website (as I'm guessing), you should save the raw input and apply the logic at render time.

See here for logic: Detect URL and add achor-tags around it

$link = preg_replace("/(http:\/\/[^\s]+)/", "<a href=\"$1\">$1</a>", $link);
Community
  • 1
  • 1
Armel Larcier
  • 15,747
  • 7
  • 68
  • 89
  • Slight improvement: Replace http with http(s?) so that either http: or https: urls are matched. – Vincent Nov 10 '22 at 06:07
0

Yo can also Try

$text = "Please visit me at my website: http://www.mywebsite.org
Please visit me at my website: http://www.mywebsite.org";
$newText    =   preg_replace('/((http|https|ftp):\/\/[^\s]+)/i',
'<a href="$1" class="link1" target="_blank">$1</a>', $text);
echo $newText;

this one

softsdev
  • 1,478
  • 2
  • 12
  • 27