我想捕获任何后面跟着换行符的HTML结束标记,并仅用HTML标记替换它们。
例如,我想把这个:
<ul>'n
<li>element</li>'n
</ul>'n'n
<br/>'n'n
Some text'n
进入这个:
<ul>
<li>element</li>
</ul>'n
<br/>'n
Some text'n
问题是我无法用regex:捕获'n
字符
preg_match_all('/(<'/[a-zA-Z]*>|<[a-zA-Z]*'/>)'n/s', $in, $matches);
一旦我将匹配数组放置在模式中的某个位置,匹配数组就会返回空值。
有趣的是,如果我只尝试单独匹配'n
字符,它会找到所有字符:
preg_match_all('/'n/s', $in, $matches);
尝试:
preg_match_all('/(<'/[a-zA-Z]*>|<[a-zA-Z]*'/>)''n/s', $in, $matches);
您必须转义"''"字符。
您可以使用以下内容:
(<[^>]+>)$'R{2}
# capture anything between a pair of < and > at the end of the line
# followed by two newline characters
您需要使用multiline
模式,请参阅regex101.com上的演示。
在PHP
中,这将是:
$regex = '~(<[^>]+>)$'R{2}~m';
$string = preg_replace($regex, "$1", $your_string_here);
一般来说,DomDocument
解析器提供了保留或丢弃空白的可能性,因此您可能更适合使用它。