簡體   English   中英

HTML 使鏈接可點擊<p>用 PHP 中的文本填充的元素

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

我遇到以下問題:我正在顯示一個文本,該文本存儲在 mySql 數據庫中的<p>元素中。 當此文本包含網址(例如: https://google.com/ )時,此網址不可點擊並突出顯示。 是否有任何解決方案可以突出顯示此<p>元素中的 url?


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

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

您可以嘗試以下具有正則表達式並按標簽包裝 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;
?>

嘗試這個:

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

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

嘗試這個?

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

在此處輸入圖片說明

要支持多個 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