Replace numbers, dash, dot or space from the start of a string with PHP regex

前端 未结 2 1317
天涯浪人
天涯浪人 2021-01-25 18:34

I\'m trying to replace numbers with optional, dash, dot or space from the start of a string, my pattern does not seem to work. I want to replace this:

01. PHP
0         


        
2条回答
  •  无人共我
    2021-01-25 18:53

    Your regex - /^[\d{0,4}(. -)?]/ - matches the beginning of the string, and then 1 character: either a digit, or a {, or a 0, or a ,, or a }, or a (, or a dot, or a range from space to ) (i.e. a space, !"#$%&' and a ), or a question mark. So, it can only work in a limited number of case you describe.

    Just use

    preg_replace('/^[\d .-]+/','', $t);
    

    Here,

    • ^ - matches beginning of string/line
    • [\d .-]+ matches a digit, space, dot or hyphen, 1 or more timesd

    See demo

    Nogte that if you have multiple lines, you need (?m) modifier.

    preg_replace('/(?m)^[\d .-]+/','', $t);
    

    Here is an IDEONE demo

    NOTE: If you plan to remove anything that is not letter from the beginning of the string, I'd recommend using ^\P{L}+ regex with u modifier.

提交回复
热议问题