0
4

1 に答える 1

0

I tried playing around with regex assertions for a while but I don't think it's possible that way as PHP doesnt seem to let me use wildcards in the lookahead/lookbehind matches.

Edit The previous example wasnt going to work with nested elements inside pre & code. This will let you capture the spacings you want to keep, remove all spacing, then put the desired spacing back in:

//$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);
}

if the tags are improperly closed, they won't fit the match pattern and thus will be skipped and have spacing stripped.

于 2012-11-27T01:23:45.917 に答える