dtwk6019 2014-07-12 12:31
浏览 27
已采纳

匹配并替换捕获/匹配的字符

I currently have a code that finds and replaces urls into complete html links. It works fine but now i need to update it so that if there is image url then it should convert it into a html img tag and display it. Function im using now is...

function auto_link_text($text) {

   $pattern  = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
   $callback = create_function('$matches', '
       $url       = array_shift($matches);
       $url_parts = parse_url($url);



       return sprintf(\'<a rel="nowfollow" target="_blank" href="%s">%s</a>\', $url, $url);
   ');

   return preg_replace_callback($pattern, $callback, $text);
}

Got it from... How to add anchor tag to a URL from text input

Here is an example of the text i would to it to go through...

asdf
http://google.com/
asfd
http://yahoo.com/logo.jpg
http://www.apple.com/sdfsd.php?page_id=13&id=18210&status=active#1
http://youtube.com/logo.png

like it updated function to output...

asdf
<a rel="nowfollow" target="_blank" href="http://google.com/">http://google.com/</a>
asfd
<img src="http://yahoo.com/logo.jpg" class="example">
<a rel="nowfollow" target="_blank" href="http://www.apple.com/sdfsd.php?page_id=13&id=18210&status=active#1">http://www.apple.com/sdfsd.php?page_id=13&id=18210&status=active#1</a>
<img src="http://youtube.com/logo.png" class="example">

Big thanks in advance!

  • 写回答

2条回答 默认 最新

  • dongweng6241 2014-07-12 13:37
    关注

    You can use this for example:

    function create_anchor_tag($url, $text = false) {
        if ($text===false) $text = $url;
        return '<a rel="no-follow" target="_blank" href="' . $url . '">'
             . $text . '</a>'; 
    }
    
    function create_image_tag($url) {
        return '<img src="' . $url . '"/>';
    }
    
    function auto_link_text($text) {
        $pattern = '~\b(?:(?:ht|f)tps?://|www\.)\S+(?<=[\PP?])~i';
    
        $callback = function ($m) {
            $img_ext = array('jpg', 'jpeg', 'gif', 'png');
            $path = parse_url($m[0], PHP_URL_PATH);
            $ext = substr(strrchr($path, '.'), 1);
    
            if (in_array(strtolower($ext), $img_ext))
                return create_image_tag($m[0]);
            return create_anchor_tag($m[0]); 
        };
    
        return preg_replace_callback($pattern, $callback, $text);
    }
    

    I used several functions to make it more clea[rn], but you can easily adapt it as you like.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。