查找字符串中的链接URL而不是图片

问题描述 投票:-5回答:1

我试图在一个字符串中找到一个不是来自于 <img>. 例如::

$string = "lorem ipsum http://google.com dolor sit amet <img src="http://img.com/img.png" />;

致:

lorem ipsum http:/google.com dolor sit amet < img src="http:/img.comimg.png" >

我试过这个。

function make_clickable($text) {
$regex = '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#';
return preg_replace_callback($regex, function ($matches) {
    return "<p><a href='{$matches[0]}' class='link'>{$matches[0]}</a></p>";
}, $text);
$matches = array();

}

小编:所以可以这样。

function make_clickable($text) {
 $regex = '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#';
 return preg_replace_callback($regex, function ($matches) {
    return "<p><a href='{$matches[0]}' class='link'>{$matches[0]}</a></p>";
 }, $text);
 $matches = array();
}

$string = preg_replace('/\bsrc="http\b/u', 'src="htt-p', $string);
$string = make_clickable($string);
$string = preg_replace('/\bsrc="htt-p\b/u', 'src="http', $string);
echo $string;
url text
1个回答
0
投票

这样就可以了。关于它如何工作的简短解释可以在代码注释中找到。

<?php

# fixed syntax error string
$string = "lorem ipsum http://google.com dolor sit amet <img src=\"http://img.com/img.png\" />";

function make_clickable($text) {
    # explode string on spaces to array
    $arr = explode(' ', $text);

    # test each array element if it contains nothing else but a website
    foreach($arr as $key => $value){
        if(preg_match('#((^https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i', $value)){
            # replace plain text urls with href links in array
            $arr[$key] = "<p><a href='". $value ."' class='link'>". $value ."</a></p>";
        }
    }

    # rebuild array back to string
    $text = implode(' ', $arr);

    # return result
    return $text;
}

echo make_clickable($string);

?>
© www.soinside.com 2019 - 2024. All rights reserved.