dryl34156 2015-04-23 05:30
浏览 15
已采纳

正则表达式删除图像周围的链接

I have a page of images wrapped with links. Essentially I want to remove the links surrounding images, but keep the image tags in tact.

eg. I have:

<a href="something.html" alt="blah"><img src="image1.jpg" alt="image 1"></a>

and I want:

<img src="image1.jpg" alt="image 1">

I tried this code I found in my research, but it leaves a stray </a> tag.

$content =
    preg_replace(
        array('{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}',
            '{ wp-image-[0-9]*" ></a>}'),
        array('<img','" />'),
        $content
    );

I have no idea when it comes to regular expressions so can someone please fix my code? :-)

  • 写回答

2条回答 默认 最新

  • douhuan7862 2015-04-23 05:40
    关注

    by your provided regex it seems you are using wordpress and want to remove hyperlinks from content.

    if you are using wordpress then you can also use this hook to remove hyper links on images from content.

    add_filter( 'the_content', 'attachment_image_link_remove_filter' );
    
    function attachment_image_link_remove_filter( $content ) {
        $content =
            preg_replace(
                array('{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}',
                    '{ wp-image-[0-9]*" /></a>}'),
                array('<img','" />'),
                $content
            );
        return $content;
    }
    

    here is the another function that will also work.

    function attachment_image_link_remove_filter($content)
        {
            $content =
                preg_replace(array('{<a[^>]*><img}', '{/></a>}'), array('<img', '/>'), $content);
            return $content;
        }
    
        add_filter('the_content', 'attachment_image_link_remove_filter');
    

    OR you can use also Demo

    $string = '<a href="something.html" alt="blah"><img src="image1.jpg" alt="image 1"></a>';
    $result = preg_replace('/<a href=\"(.*?)\">(.*?)<\/a>/', "\\2", $string);
    echo $result; // this will output "<img src="image1.jpg" alt="image 1">"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题