我将有一个由HTML代码组成的字符串(一行),该代码将存储在PHP变量中。这个字符串来自一个HTML页面,该页面通常在标记之间有换行符和空格。我们可以有新的行(一个或多个)和,或像这样的空白豁免:
<h1>tag1</h>
<p>Between h ad p we have 's and 'n</p>
在执行regex和preg_replace之后,我想要这个:
<h1>tag1</h><p>Between h ad p we have 's and 'n</p>
我试过这个正则表达式,但它不起作用。
$str=<<<EOF
<h1>tag1</h>
<p>Between h ad p we have 's and 'n</p>
EOF;
$string = trim(preg_replace('/(>'s+<)|(>'n+<)/', ' ', $str));
在这里你可以找到整个代码http://www.phpliveregex.com/p/7Pn
有两个问题
(preg_replace('/(>'s+<)|(>'n+<)/', ' ', $str)
CCD_ 1已经包括CCD_。
(>'s+<)
这里正则表达式同时消耗角度<
和>
,因此用空格替换将删除包括角度在内的所有内容
输出为
<h1>tag1</hp>Between h ad p we have 's and 'n</p>
这不是你想要的
如何更正
使用正则表达式><
和替换字符串作为(?<=>)'s+(?=<)
,输出为
<h1>tag1</h><p>Between h ad p we have 's and 'n</p>
例如http://regex101.com/r/dI1cP2/2
你也可以使用环视来解决的问题
正则表达式将是
(?<=>)
并且替换字符串将是空字符串
解释
's
0断言>
被's+
预编码
(?=<)
匹配一个或多个空间
's
断言<
后面跟着empty string
在这里,lookaround将不会像早期的regex 中那样使用任何尖括号
参见http://regex101.com/r/dI1cP2/3例如
您可以尝试以下操作:
echo preg_replace("/(?='>'s+'n|'n)+('s+)/", "", $str);
(?<=<'/h>)'s+
试试这个。请参阅演示。替换为CCD_17
http://regex101.com/r/jI8lV7/1