2014-10-31 110 views
0

在我们的一些文章中,我们发现图像错误地将硬链接硬编码到图像标签的标题/ alt属性中,导致图像显示中断。例如:从图像标签的标题和alt属性中去除HTML标签

<img src="/imgs/my-image.jpg" title="This is a picture of a <a href="/blob.html">blob</a>." /> 

我使用preg_replace_callback函数试过了,但它是难以企及的,因为从链接重复报价的全名。

我希望能够以编程方式为任何字符串执行此操作以确保正确的输出。想法?

+0

为什么不使用HTML编辑器的Ctrl + H功能? – DividedByZero 2014-10-31 21:08:23

+1

'strip_tags'函数? – 2014-10-31 21:08:38

+0

@u_mulder:问题是要剥离的标签位于HTML属性中。 – 2014-10-31 21:09:03

回答

0

你可以尝试这种模式:

$pattern = <<<'EOD' 
~ 
(?: 
    \G(?!\A)     # second entry point 
    (?:      # content up to the next alt/title attribute (optional) 
     [^><"]* "     # end of the previous attribute 
     (?> [^><"]* " [^"]* ")*? # other attributes (optional) 
     [^><"]*     # spaces or attributes without values (optional) 
     \b(?:alt|title)\s*=\s*" # the next alt/title attribute 
    )?+      # make all the group optional 
    | 
    <img\s[^>]*?    # first entry point 
    \b(?:alt|title)\s*=\s*" 
) 
[^<"]*+\K 
(?:    # two possibilities: 
    </?a[^>]*>  # an "a" tag (opening or closing) 
    |    # OR 
    (?=")   # followed by the closing quote 
) 
~x 
EOD; 

$result = preg_replace($pattern, '', $html); 

online demo

这种模式的使用与\G锚重复比赛的连续性。

+0

这适用于我的场景!唯一的缺陷就是它只能在第一个实例上工作,所以如果同时存在title和alt属性和链接,它只会替换第一个(而不是我个案中的问题)。谢谢! – tustind 2014-11-01 02:26:56

+0

@tindind:的确,我认为它现在已经得到纠正。 *(旧版本在alt和title之间存在一个或多个其他属性时不起作用。)* – 2014-11-01 09:47:52