Vladimir Hraban
Vladimir Hraban

Reputation: 3581

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.

Upvotes: 0

Views: 225

Answers (2)

mickmackusa
mickmackusa

Reputation: 47864

Regex is overkill / not necessary. PHP already has ltrim() for this task -- just whitelist the characters to be trimmed. Use double-dot range syntax for brevity. Demo

$vat = 'es7782173x';
echo ltrim($vat, 'a..z');  // remove leading lowercase letters

echo ltrim($vat, 'A..Z');  // remove leading uppercase letters

echo ltrim($vat, 'a..zA..Z');  // remove leading letters

The inverse is to whitelist the characters which mark the start of the substring to keep. This strpbrk() doesn't currently recognize double-dot range syntax. Demo

echo strpbrk($vat, '0123456789');

Character masks are single-byte characters formed as a single string; character order doesn't matter at all.

Learn more about functions which use double-dot range syntax in their character mask parameter at Native PHP functions that allow double-dot range syntax

Upvotes: 1

knittl
knittl

Reputation: 265161

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.

Upvotes: 4

Related Questions