【问题标题】:Detect and convert url in link and detect image and convert to img PHP检测并转换链接中的url并检测图像并转换为img PHP
【发布时间】:2017-03-01 16:35:24
【问题描述】:

目前,我使用此代码来检测和转换文本链接中的 URL。

但现在,我需要保留这个系统,但也要检测和转换图像。

public function convert_to_link($text)
{
    $reg_user = '!@(.+)(?:\s|$)!U';
    if (preg_match_all($reg_user, $text, $matches))
    {
        return preg_replace($reg_user, '<a href="../userdetails.php?uname=$0" title="$0">$0</a>', $text);
    }
    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    if(preg_match($reg_exUrl, $text, $url)) {
        // make the urls hyper links
        if (preg_match("/\[img=([^\s'\"<>]+?)\]/i", $text))
        {
           //This is not working
            return preg_replace("/\[img=([^\s'\"<>]+?)\]/i", "<img border=0 src=\"\\1\">", $text);
        }
        else
        {
            return preg_replace($reg_exUrl, '<a href="$0" title="$0">$0</a> ', $text);
        }
    }
    else
    {
        return $text;
    }
}

我也使用 [img][/img] 代码将图像转换为,但使用上面的代码,结果很糟糕:

【问题讨论】:

    标签: php html regex image


    【解决方案1】:

    看起来您的正则表达式正在寻找这种格式

    [img=http://example.com/name.png]
    

    但您的示例格式不同

    [img]http://example.com/name.png[/img]
    

    识别第二种形式的正则表达式是

    "/^\[img\]([^\[]+)\[\/img\]$/i"
    

    【讨论】:

    猜你喜欢
    • 2016-07-02
    • 2018-11-14
    • 2018-02-10
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多