'Regex to remove links surrounding images
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? :-)
Solution 1:[1]
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">"
Solution 2:[2]
You can use <a.*?(<img.*?>)<\/a> to match and replace with $1
See DEMO
$content = preg_replace('/<a.*?(<img.*?>)<\/a>/', '$1', $content);
Solution 3:[3]
I think that
$content = preg_replace('/<a\s+href=[^>]+>(<img[^>]+>)<\/a>/', '$1', $content);
is a better solution.
Ex : https://regex101.com/r/3ozruM/1
Because @karthik manchala's solution https://regex101.com/r/ETkE58/1 doesn't work in such a case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Paul ALBERT |
