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

前端 未结 2 1309
天涯浪人
天涯浪人 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:37

    Can try this

    $t = "01. PHP";
    
    $pattern = '/^[0-9\.\s\-]+/';
    
    echo preg_replace($pattern, '', $t);
    

    Output

    PHP
    

    Regex Explanation

    ^ assert position at start of the string
    0-9 a single character in the range between 0 and 9
    \. matches the character . literally
    \s match any white space character [\r\n\t\f ]
    \- matches the character - literally
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题