【问题标题】:Regex to remove links surrounding images正则表达式删除图像周围的链接
【发布时间】:2015-04-23 05:30:00
【问题描述】:

我有一页带有链接的图片。本质上,我想删除图像周围的链接,但保持图像标签完好无损。

例如。我有:

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

我想要:

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

我尝试了我在研究中发现的这段代码,但它留下了一个杂散的&lt;/a&gt; 标记。

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

我不知道什么时候涉及正则表达式,所以有人可以修复我的代码吗? :-)

【问题讨论】:

  • 你在用wordpress吗?

标签: php regex preg-replace


【解决方案1】:

您可以使用&lt;a.*?(&lt;img.*?&gt;)&lt;\/a&gt;来匹配和替换$1

DEMO

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

【讨论】:

  • 嗯。好像不太喜欢那个给我一个警告:'没有结尾匹配分隔符'>'
  • @henZa 忘记了/.../ 的正则表达式.. 请检查更新的答案:)
【解决方案2】:

根据您提供的正则表达式,您似乎正在使用 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');

或者你也可以使用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">"

【讨论】:

  • 是的。正是我在做什么。不过,您的解决方案似乎仍然留下了那个杂散的链接结束标记......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
  • 2010-10-23
  • 2010-10-31
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多