Home > Mobile >  How can I remove only numbers an the beginning of a string and not at the end of a string with PHP?
How can I remove only numbers an the beginning of a string and not at the end of a string with PHP?

Time:11-18

for Example:

39P -> must become P

208Pb ->must become Pb

but: CaSO4 -> must stay CaSO4

(not remove number in CaSO4 )

CodePudding user response:

You could use ltrim.

$s = '208Pb';
echo ltrim($s, '0123456789');
# Pb

You could write a regular expression.

echo preg_replace('[^\d ]', '', $s);
# Pb

You could parse the string using sscanf with a default in case it fails.

echo sscanf($s, '%d%s')[1] ?: $s
# Pb

You could use substr and strspn.

echo substr($s, strspn($s, '0123456789'));
# Pb

You could write a little loop.

while ($s !== '' && is_numeric($s[0])) $s = substr($s, 1); echo $s;
# or, if your leading numbers cannot possibly be just a bunch of zeros:
while ($s > 0) $s = substr($s, 1); echo $s;
# Pb

CodePudding user response:

Use left trim with a ranged mask.

echo ltrim($string, '0..9');

  • Related