2014-10-31 111 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