Search code examples
phpstringtrimletter

Trim leading letters from a string


I have a list of VAT numbers. The problem is, some of them contain a two-character country ISO code in the beginning, others do not.

I need to strip those 2 letters if they exist, for example, es7782173x becomes 7782773x and 969652255801 remains the same.


Solution

  • A PHP regex to replace all letters from the beginning:

    $vat = 'es7782173x';
    $vat = preg_replace('/^\D+/', '', $vat);
    

    \D matches anything that is not a digit, and replacing it with the empty string '' effectively strips it from the beginning (^ anchor). + matches 1 or more occurrences.