我有一页用链接包装的图片。本质上,我想删除链接周围的图像,但保持形象标签的机智。
例如:我有:
<a href="something.html" alt="blah"><img src="image1.jpg" alt="image 1"></a>我想:
<img src="image1.jpg" alt="image 1">我尝试了我在我的研究中发现的这段代码,但是它留下了一个</a>标签。
$content =
preg_replace(
array('{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}',
'{ wp-image-[0-9]*" ></a>}'),
array('<img','" />'),
$content
);当涉及正则表达式时,我不知道,所以请有人修复我的代码吗?:-)
发布于 2015-04-23 05:40:51
通过您提供的regex,您似乎正在使用wordpress,并希望从内容中删除超链接。
如果您正在使用wordpress,那么您也可以使用这个钩子从内容中删除图片上的超链接。
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;
}这是另一个也能工作的功能。
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');或者您也可以使用演示
$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">"发布于 2015-04-23 05:40:55
您可以使用<a.*?(<img.*?>)<\/a>来匹配和替换$1
请参阅演示
$content = preg_replace('/<a.*?(<img.*?>)<\/a>/', '$1', $content);发布于 2022-04-08 16:01:08
我认为
$content = preg_replace('/<a\s+href=[^>]+>(<img[^>]+>)<\/a>/', '$1', $content);
是个更好的解决办法。
例:https://regex101.com/r/3ozruM/1
因为@karthik的解决方案https://regex101.com/r/ETkE58/1在这种情况下不起作用。
https://stackoverflow.com/questions/29814468
复制相似问题