0

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?

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user2335065
  • 2,337
  • 3
  • 31
  • 54

1 Answers1

2

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

Use

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

Details

  • ^ - 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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563