Search code examples
phpstringsubstrstrpos

Trim all characters before an integer in a string in PHP?


I have an alpha numeric string say for example,

abc123bcd , bdfnd567, dfd89ds.

I want to trim all the characters before the first appearance of any integer in the string.

My result should look like,

abc , bdfnd, dfd.

I am thinking of using substr. But not sure how to check for a string before first appearance of an integer.


Solution

  • You can easily remove the characters you don't want with preg_replace [docs] and a regular expression:

    $str = preg_replace('#\d.*$#', '', $str);
    

    \d matches a digit and .*$ matches any character until the end of the string.

    Learn more about regular expressions: http://www.regular-expressions.info/.

    DEMO