问问题
557 次
1 回答
0
我尝试使用正则表达式断言一段时间,但我认为这不可能,因为 PHP 似乎不允许我在前瞻/后瞻匹配中使用通配符。
编辑 前面的示例不能使用 pre & 代码中的嵌套元素。这将让您捕获要保留的间距,删除所有间距,然后将所需的间距放回:
//$html is your initial html string with line returns and spaces
//pattern to match open tag, inner content and closing tag
$pattern = '/<(pre|code)((?!<\/?\1).)*?<\/\1>/s';
//before: capture the string pattern of the multiline elements
preg_match_all($pattern, $html, $before);
//remove all LF, CR and indentation tabs
$html = preg_replace('/(\t|\r|\n)/s', '', $html);
//after: capture the string pattern of the condensed elements
preg_match_all($pattern, $html, $after);
//loop through the matches to replace the after with the before
foreach($after[0] as $k => $v){
$html = str_replace($v, $before[0][$k], $html);
}
如果标签未正确关闭,它们将不适合匹配模式,因此将被跳过并去除间距。
于 2012-11-27T01:23:45.917 回答