Regex to remove links surrounding images

时间:2015-04-23 05:30:01

标签: php regex preg-replace

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 个答案:

答案 0 :(得分:3)

You can use <a.*?(<img.*?>)<\/a> to match and replace with $1

See DEMO

$content = preg_replace('/<a.*?(<img.*?>)<\/a>/', '$1', $content);

答案 1 :(得分:2)

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">"