Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 正则表达式中的奇怪行为_Php_Regex_Preg Replace_Newline_Pcre - Fatal编程技术网

Php 正则表达式中的奇怪行为

Php 正则表达式中的奇怪行为,php,regex,preg-replace,newline,pcre,Php,Regex,Preg Replace,Newline,Pcre,我正在替换标记的空行。 正则表达式替换所有允许空白(\s)的黑线,作为一个标记 例如,此字符串: $string="with.\n\n\n\nTherefore"; 但是返回2个标签 所以,我做了这个测试:(这不是为了替换,只是为了测试) 并检查返回的内容: with. []| |()[]||() Therefore 想象: with.\n ^\n \n $^\n$\n Therefore 正则表达式添加一个\n,第四个不执行“她”必须执行的操作。(跳到另一行) 能帮忙的人。 基本上是解

我正在替换
标记的空行。 正则表达式替换所有允许空白(\s)的黑线,作为一个
标记

例如,此字符串:

$string="with.\n\n\n\nTherefore";
但是返回2个标签

所以,我做了这个测试:(这不是为了替换,只是为了测试)

并检查返回的内容:

with.
[]|

|()[]||()
Therefore
想象:

with.\n
^\n
\n
$^\n$\n
Therefore
正则表达式添加一个\n,第四个不执行“她”必须执行的操作。(跳到另一行)

能帮忙的人。 基本上是解释问题,而不是解决问题。
谢谢evryone。

您的正则表达式应至少匹配一个空格字符。因此,用
\s+
替换
\s*
,或者如果需要转义
\s\+


\s*
将匹配每一个字符,这是因为它匹配任何(
*
)空格(
\s
),并且因为任何空格,它都不包含任何字符。“无”是指字符串“abc”
\s*
将匹配“
^
”和“
a
”、“
a
”和“
b
”、“
b
”和“
c
”、“
c
”和“
$/code>”之间的“空”字符

在linux终端上进行测试非常容易,如下所示:

$ echo "abc" | sed 's:\s*:\n:g'  # replace \s* with \n for the whole string 

a
b
c

$ # ^ the result
如您所见,它匹配每个“空”字符,并将其替换为
\n


另一方面,
\s+
将强制正则表达式至少匹配1个(
+
)空格(
\s
)字符,因此它可以正常工作

好的,谢谢,这是有用的,你知道一本书可以解释正则表达式引擎是如何工作的吗?请检查这两个问题:和
$ echo "abc" | sed 's:\s*:\n:g'  # replace \s* with \n for the whole string 

a
b
c

$ # ^ the result