最近遇到一個問題,有些客戶會去其他網站複製內容,然後再貼到自己的網站。使用這樣複製會遇到一個問題,就是會連其他網站所設定的style樣式都跟著複製起來,因此客戶將內容貼回自己的網站時,會出現版面不合、破版等....問題。然後客戶就抱怨我們系統有問題=.=

如果你有跟我一樣的困擾,可以使用preg_replace函數,透過正規表示法將HTML標籤的行內style通通去除掉這樣就搞定啦~

例如像這樣:

<p style="width:1500px;margin:10px;color:#fff;">aidectw</p>

或這樣

<a href="https://blog.aidec.tw/tags/AI%E6%8A%80%E8%A1%93" class="tag" style="box-sizing: border-box; background: rgb(233, 233, 233); color: rgb(153, 153, 153); text-decoration-line: none; border-radius: 3px 0px 0px 3px; display: inline-block; height: 26px; line-height: 26px; padding: 0px 20px 0px 23px; position: relative; margin: 0px 10px 10px 0px; transition: color 0.2s ease 0s;">AI技術</a>

去除之後就會只剩

<p>aidectw</p>

<a href="https://blog.aidec.tw/tags/AI%E6%8A%80%E8%A1%93" class="tag" >AI技術</a>

preg_replace去除style

preg_replace去除style

preg_replace語法

preg_replace(正規表示法, 替代內容, 原始內容);

了解preg_replace的使用方式後,我們便可以利用它實現去除HTML標籤內的style元素。

$result = preg_replace('/style=\\"[^\\"]*\\"/', '', $content); 

使用正規表示法/style=\\"[^\\"]*\\"/,匹配所有的標籤內style,並將所有匹配的內容通通替代為空字串。

雖然說此種方法能去除所有標籤內style,但無法指定保留特定的style元素,若你有想到怎麼做,歡迎在下面留言啊~



文章轉載或引用,請先告知並保留原文出處與連結!!(單純分享或非營利的只需保留原文出處,不用告知)

原文連結:
https://blog.aidec.tw/post/php-remove-all-inline-css