我如何使用 php 去除标签中的所有/任何属性,比如段落标签?
<p class="one" otherrandomattribute="two">
至 <p>
最佳答案
虽然有更好的方法,但您实际上可以使用正则表达式从 html 标签中去除参数:
<?php
function stripArgumentFromTags( $htmlString ) {
$regEx = '/([^<]*<\s*[a-z](?:[0-9]|[a-z]{0,9}))(?:(?:\s*[a-z\-]{2,14}\s*=\s*(?:"[^"]*"|\'[^\']*\'))*)(\s*\/?>[^<]*)/i'; // match any start tag
$chunks = preg_split($regEx, $htmlString, -1, PREG_SPLIT_DELIM_CAPTURE);
$chunkCount = count($chunks);
$strippedString = '';
for ($n = 1; $n < $chunkCount; $n++) {
$strippedString .= $chunks[$n];
}
return $strippedString;
}
?>
上面的内容可能用更少的字符写,但它完成了工作(快速而肮脏)。
关于php - 如何从 html 标签中删除属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/770219/