匹配 PHP 中多行字符串中每行开头的任何水平空白字符 [英] Match any horizontal whitespace characters at the start of each line in multiline strings in PHP

查看:52
本文介绍了匹配 PHP 中多行字符串中每行开头的任何水平空白字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换所有新行开头的所有空格.我有两个正则表达式替换:

I want to replace all empty spaces on the beginning of all new lines. I have two regex replacements:

$txt = preg_replace("/^ +/m", '', $txt);
$txt = preg_replace("/^[^\S\r\n]+/m", '', $txt);

它们中的每一个都匹配不同类型的空格.但是,可能有两个空格都存在且顺序不同,因此我想在新行的开头匹配所有空格的出现.我该怎么做?

Each of them matches different kinds of empty spaces. However, there may be chances that both of the empty spaces exist and in different orders, so I want to match occurences of all of them at the beginning of new lines. How can I do that?

注意:第一个正则表达式匹配一个表意空间\u3000字符,它只能在质疑原始正文(所以渲染在这里没有做正确的工作).第二个正则表达式仅匹配 LF 和 CR 以外的 ASCII 空白字符.这是一个演示 证明第二个正则表达式与第一个正则表达式匹配的内容不匹配.

NOTE: The first regex matches an ideographic space, \u3000 char, which is only possible to check in the 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 proving the second regex does not match what the first regex matches.

推荐答案

由于您想从需要使用的 Unicode 字符串中删除任何水平空白

Since you want to remove any horizontal whitespace from a Unicode string you need to use

  • \h regex escape ("any horizontal whitespace character (since PHP 5.2.4)")
  • u modifier (see Pattern Modifiers)

使用

$txt = preg_replace("/^\h+/mu", '', $txt);

详情

  • ^ - 一行的开始(m 修饰符使 ^ 匹配所有行的起始位置,而不仅仅是字符串的起始位置)
  • \h+ - 一个或多个水平空格
  • u 修饰符将确保 Unicode 文本被视为 Unicode 代码点序列,而不仅仅是代码单元,并使模式中的所有正则表达式转义符都能识别 Unicode.
  • ^ - start of a line (m modifier makes ^ match all line start positions, not just string start position)
  • \h+ - one or more horizontal whitespaces
  • u modifier will make sure the Unicode text is treated as a sequence of Unicode code points, not just code units, and will make all regex escapes in the pattern Unicode aware.

这篇关于匹配 PHP 中多行字符串中每行开头的任何水平空白字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆