i use this to check if there is a 06 number in the string. the 06 number is always 10 numbers.
$string = "This is Henk 0612345678";
$number = preg_replace('/[^0-9.] /', '', $string);
echo $number;
This is working good, but when the string is
$string = "This is 12Henk 0612345678";
The number is 120612345678 I dont want the 12 into it, but 12 is not always the same in the string. How can i check only for a 10 digits number ?
Thanks
CodePudding user response:
This could help you
/([ \w] )(06[0-9. ]{8})/
the 1st () is the entire String before the 06 and the 2nd() is the Number starting with 06 and 8 digits.
The solution does not cover the case where a 06 comes before the number sequence
CodePudding user response:
Rather than replacing everything that's not what you want, try searching for what you do want with preg_match.
That makes it a lot easier to be specific:
- The number always starts
06
, so you can hard-code that in your regex - That's followed by exactly 8 more digits, which you can specify as
[0-9]{8}
or\d{8}
("d" for "digit") - To avoid matching longer numbers, you can surround that with
\b
for "word break"
Put it together, and you get:
preg_match('/\b06\d{8}\b/', $string, $matched_parts);
This doesn't change $string
, but gives you an array in $matched_parts
containing the matched parts; see the preg_match documentation for a detailed explanation.