I have phone number. If the first numeric character of a number is not 1 I need to add it. I can't find out how to do it with preg_match, or is there any other way?
$first_number = $number;
if(preg_match('something', $first_number, $result))
{
$first_number = '1'. $result[1];
}
There is not need to go for regex here. You can do:
if($first_number[0] != '1') {
$first_number = '1'.$first_number;
}
But if the number can have leading spaces or a +
sign you can do:
if(preg_match('/^(\D*)(\d)/',$first_number,$match))
$first_number = $match[1].'1'.$match[2];
}
No need to use preg_match
or preg_replace
here, the simple solution below should work
if ($number[0] != 1)
{
$number.= '1'. $number;
}
use
'/^([^1][0-9]+)$/'
It should do the trick!
The first non-numeric character isn't always at position 1 in the array, if I'm reading your question right.
$n="foo 415";
preg_match("/^[^0-9]*([0-9])/", $n, $matches);
print $matches[0]."
";'
returns 4
.