V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
GASALA
V2EX  ›  问与答

一个正则的问题

  •  
  •   GASALA · 2013-04-19 10:56:54 +08:00 · 2336 次点击
    这是一个创建于 4038 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在wordpress中想实现发布文章贴图片网址就直接显示图片,参照网上的代码写了一段这样的,没效果。

    function embed_images($content){$embed_images = preg_replace_callback('/((^http[s]{0,1}:)\/\/(.+).(gif|jpg|bmp|png))/i', "addimg",$content);return $embed_images;}

    function addimg($url){global $post;$title = $post ->post_title;$imgurl = preg_replace('/((^http[s]{0,1}:)\/\/(.+).(gif|jpg|bmp|png))/i', '<img src="$1" alt="'.$title.'" />',$url[0]);if($imgurl !== $url[0]){return $imgurl;}}}add_filter(the_content', 'embed_images');

    但是改成下面的就可以显示图片了(相比上面的只替换了第一段的正则),不过这个同时把正文的网址链接也直接去掉了。怎样能显示图片,但是不要删除链接呢?求解。。。

    function embed_images($content){$embed_images = preg_replace_callback('/https?:\/\/([A-z0-9]+[_\-]?[A-z0-9]+\.)*[A-z0-9]+\-?[A-z0-9]+\.[A-z]{2,}(\/.*)*\/?/i', "addimg",$content);return $embed_images;}

    function addimg($url){global $post;$title = $post ->post_title;$imgurl = preg_replace('/((^http[s]{0,1}:)\/\/(.+).(gif|jpg|bmp|png))/i', '<img src="$1" alt="'.$title.'" />',$url[0]);if($imgurl !== $url[0]){return $imgurl;}}}add_filter(the_content', 'embed_images');
    7 条回复    1970-01-01 08:00:00 +08:00
    ljbha007
        1
    ljbha007  
       2013-04-19 11:11:25 +08:00
    下次最好贴gist 这代码没缩进看着真心累

    把第二个函数里边的正则替换改一下就好了

    https://gist.github.com/CarlLee/5417857
    ljbha007
        2
    ljbha007  
       2013-04-19 11:18:12 +08:00
    ljbha007
        3
    ljbha007  
       2013-04-19 11:18:23 +08:00
    贴个gist真麻烦!!
    GASALA
        4
    GASALA  
    OP
       2013-04-19 11:39:33 +08:00
    @ljbha007 抱歉哦,因为之前贴gist也是只能出来网址。

    刚试了一下,还是不行哦,其它除了图片地址之外的的网址还是被清除了。包括链接,视频链接。
    ljbha007
        5
    ljbha007  
       2013-04-19 11:49:03 +08:00
    @GASALA 你是这个意思啊
    又改了一下 这下没问题了

    http://gist.github.com/5417857
    ljbha007
        6
    ljbha007  
       2013-04-19 12:02:39 +08:00   ❤️ 1
    又写了个更简单的版本

    http://gist.github.com/5418071
    GASALA
        7
    GASALA  
    OP
       2013-04-19 12:09:43 +08:00
    @ljbha007 哇塞。厉害,没有任何问题。非常感谢^_^
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   958 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:44 · PVG 04:44 · LAX 13:44 · JFK 16:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.