简体   繁体   English

HTML 使链接可点击<p>用 PHP 中的文本填充的元素

[英]HTML make link clickable in <p> element filled with text from PHP

I got following problem: I am displaying a text, stored in mySql Database in an <p> element.我遇到以下问题:我正在显示一个文本,该文本存储在 mySql 数据库中的<p>元素中。 When this text is containing an url (eg: https://google.com/ ) this url is not clickable and highlighted.当此文本包含网址(例如: https://google.com/ )时,此网址不可点击并突出显示。 Is there any solution to highlight an url in this <p> element?是否有任何解决方案可以突出显示此<p>元素中的 url?


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

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

You can try the below code which has regular expression and wraps the URLs by tag.您可以尝试以下具有正则表达式并按标签包装 URL 的代码。 This works universally for any type of the 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;
?>

Try this:尝试这个:

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

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

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>

在此处输入图片说明

To support multiple URLs following code is the right one!要支持多个 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM