匹配 PHP 中多行字符串中每行开头的任何水平空白字符
Match any horizontal whitespace characters at the start of each line in multiline strings in PHP
我想替换所有新行开头的所有空 space。我有两个正则表达式替换:
$txt = preg_replace("/^ +/m", '', $txt);
$txt = preg_replace("/^[^\S\r\n]+/m", '', $txt);
他们每个人都匹配不同种类的空spaces。但是,可能有两个空的 space 都存在并且顺序不同,所以我想在新行的开头匹配所有它们的出现。我该怎么做?
注意:第一个正则表达式匹配一个 表意文字 space, \u3000
字符,这是唯一可能的检查 question raw body (SO rendering is not doing the right job here). The second regex matches only ASCII whitespace chars other than LF and CR. Here is a demo 证明第二个正则表达式与第一个正则表达式匹配的内容不匹配。
因为你想从你需要使用的 Unicode 字符串中删除任何水平空格
\h
regex escape ("any horizontal whitespace character (since PHP 5.2.4)")
u
修饰符(参见Pattern Modifiers)
使用
$txt = preg_replace("/^\h+/mu", '', $txt);
详情
^
- 行的开始(m
修饰符使 ^
匹配所有行的开始位置,而不仅仅是字符串开始位置)
\h+
- 一个或多个水平空格
u
修饰符将确保 Unicode 文本被视为一系列 Unicode 代码点,而不仅仅是代码单元,并且将使模式中的所有正则表达式转义都识别 Unicode。
我想替换所有新行开头的所有空 space。我有两个正则表达式替换:
$txt = preg_replace("/^ +/m", '', $txt);
$txt = preg_replace("/^[^\S\r\n]+/m", '', $txt);
他们每个人都匹配不同种类的空spaces。但是,可能有两个空的 space 都存在并且顺序不同,所以我想在新行的开头匹配所有它们的出现。我该怎么做?
注意:第一个正则表达式匹配一个 表意文字 space, \u3000
字符,这是唯一可能的检查 question raw body (SO rendering is not doing the right job here). The second regex matches only ASCII whitespace chars other than LF and CR. Here is a demo 证明第二个正则表达式与第一个正则表达式匹配的内容不匹配。
因为你想从你需要使用的 Unicode 字符串中删除任何水平空格
\h
regex escape ("any horizontal whitespace character (since PHP 5.2.4)")u
修饰符(参见Pattern Modifiers)
使用
$txt = preg_replace("/^\h+/mu", '', $txt);
详情
^
- 行的开始(m
修饰符使^
匹配所有行的开始位置,而不仅仅是字符串开始位置)\h+
- 一个或多个水平空格u
修饰符将确保 Unicode 文本被视为一系列 Unicode 代码点,而不仅仅是代码单元,并且将使模式中的所有正则表达式转义都识别 Unicode。