3

I got following problem: I am displaying a text, stored in mySql Database in an <p> element. When this text is containing an url (e.g: https://google.com/) this url is not clickable and highlighted. Is there any solution to highlight an url in this <p> element?


$projectDescription = "Some text..Link1: https://google.com/";

<p class="project-overview-text"><?php echo($projectDescription); ?></p>

profidash_98
  • 321
  • 2
  • 4
  • 19

4 Answers4

2

You can try the below code which has regular expression and wraps the URLs by tag. This works universally for any type of the URL

<?php

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

        //your text
        $projectDescription = "Some text..Link1: https://google.com/";

        // Checking if any url is present in the text
        if(preg_match($reg_exUrl, $projectDescription, $url)) {
               // Wrap urls by <a>
               $projectDescription = preg_replace($reg_exUrl, '<a href="'.$url[0].'">'.$url[0].'</a> ', $projectDescription);
        } 

        echo $projectDescription;
?>
1

Try this:

    $projectDescription = "Some text..Link1: https://google.com/";

<p class="project-overview-text"><a href="your_link_here"><?php echo($projectDescription); ?></a></p>
Murtaza Ahmad
  • 267
  • 1
  • 5
  • 16
0

Try this?

<?php
$projectDescription = "Some text..Link1: https://google.com/"; 
$position_http = strpos($projectDescription,"http") ;
$position_com = strpos($projectDescription,"com") ;

$url = substr($projectDescription, $position_http, $position_com+2);
?>
<p class="project-overview-text"><?php echo substr($projectDescription, 0, $position_http);?>
<a href="<?php echo $url?>" class="project-overview-text"><?php echo($url); ?></a> </p>

enter image description here

Nova
  • 364
  • 1
  • 15
  • 1
    If you have multiple urls in a string, @Jairus Martin's suggestion: https://stackoverflow.com/questions/36564293/extract-urls-from-a-string-using-php will be a better idea. – Nova Dec 11 '19 at 06:20
0

To support multiple URLs following code is the right one!

$regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i';
preg_match_all($regex, $projectDescription, $matches);
$urls = $matches[0];

// go over all links
foreach($urls as $url) {
   $projectDescription = str_replace($url, '<a href="'.$url.'">'.$url.'</a> ', $projectDescription);
}
profidash_98
  • 321
  • 2
  • 4
  • 19