HTML使链接可以在<p>元素中单击,并用PHP

时间:2019-12-05 21:01:31

标签: php html hyperlink

我遇到以下问题: 我正在显示文本,该文本存储在mySql数据库的<p>元素中。 当此文本包含网址(例如https://google.com/)时,该网址不可点击并突出显示。 有什么解决办法可以突出显示此<p>元素中的网址?


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

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

4 个答案:

答案 0 :(得分:1)

尝试一下:

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

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

答案 1 :(得分:1)

您可以尝试下面的代码,该代码具有正则表达式并按标记将URL包裹起来。普遍适用于任何类型的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;
?>

答案 2 :(得分:0)

尝试一下?

<?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

答案 3 :(得分:0)

要支持多个URL,以下代码是正确的!

$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);
}