Match any horizontal whitespace characters at the start of each line in multiline strings in PHP

前端 未结 1 1067
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 03:44

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_rep         


        
相关标签:
1条回答
  • 2021-01-29 04:06

    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)

    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.
    0 讨论(0)
提交回复
热议问题