這是最好的我能想出
$re = "/\sstyle\=('|\").*?(?<!\\\\)\1/i";
$str = "<a href=\"link.html\" style=\"color:#FF0000;\"\" class=\"someclass\">Link</a>";
$subst = '';
$result = preg_replace($re, $subst, $str, 1);
輸出
<a href="link.html" class="someclass">Link</a>
演示:
http://regex101.com/r/uW2kB8/8
說明:
\s match any white space character [\r\n\t\f ]
style matches the characters style literally (case insensitive)
\= matches the character = literally
1st Capturing group ('|")
1st Alternative: '
' matches the character ' literally
2nd Alternative: "
" matches the character " literally
.*? matches any character (except newline)
Quantifier: Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
(?<!\\) Negative Lookbehind - Assert that it is impossible to match the regex below
\\ matches the character \ literally
\1 matches the same text as most recently matched by the 1st capturing group
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
甚至會處理這樣的情況。
<a href="link.html" style="background-image:url(\"..\somimage.png\");" class="someclass">Link</a>
和
<a href="link.html" style="background-image:url('..\somimage.png');" class="someclass">Link</a>
和(它不會刪除)
<a href="link.html" data-style="background-image:url('..\somimage.png');" class="someclass">Link</a>
甚至
<a href='link.html' style='color:#FF0000;' class='someclass'>Link</a>
http://regex101.com/r/uW2kB8/11
不像其他建議:)
謝謝。非常感激! – JROB
你應該添加\ s?可選的領先空間就在風格之前,或者你留下一個雙倍空間,:-p,也是你的第二個離開「鏈接」,因爲沒有捕獲組,並且你匹配標籤的起始<標籤 – ArtisticPhoenix
@ArtisiticPhoenix同意。更新。 –