'How to find the first 4 digit number in a string?
Let's say I have a string:
$string = "12, 123, 1234, 12345, 56, 567, 5678";
And I want to return the first 4 digit number in the string only.
I have a few thoughts on how I could do this, for example using:
explode(" ", $string)
And then perhaps
substr_count()
But I am not really sure how to return the first 4 digit number only, I have seen some examples of regex being used, but I don't think that would apply here.
Solution 1:[1]
You could explode it with explode(", ",$string), and then loop through the result like this
function first4digit($string){
$nums=explode(", ",$string);
foreach($nums as $num){
if(strlen($num)==4){
return $num;
}
}
}
Here is a demo for it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
