簡體   English   中英

將文本字符串中的任何 url 替換為可點擊的 php 鏈接

[英]replace any url's within a string of text, to clickable links with php

假設我有一串文本,例如

$text = "Hello world, be sure to visit http://whatever.com today";

我如何(可能使用正則表達式)插入鏈接的錨標記(將鏈接本身顯示為鏈接文本)?

您可以使用正則表達式來做到這一點:

$html_links = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', $text);

我寫了這個函數。 它替換字符串中的所有鏈接。 鏈接可以采用以下格式:

第二個參數是鏈接的目標('_blank'、'_top'...可以設置為false)。 希望能幫助到你...

public static function makeLinks($str, $target='_blank')
{
    if ($target)
    {
        $target = ' target="'.$target.'"';
    }
    else
    {
        $target = '';
    }
    // find and replace link
    $str = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.~]*(\?\S+)?)?)*)@', '<a href="$1" '.$target.'>$1</a>', $str);
    // add "http://" if not set
    $str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" '.$target.'>', $str);
    return $str;
}

編輯:添加波浪號以使網址更好地工作https://regexr.com/5m16v

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM