In PHP I have a list of country telephone codes. e.g: US 1, Egypt 20 ....
I need to check if a given string starts with 00[ANY NUMBER FROM THE LIST].
How can I achieve this and return the country code?
Asked
Active
Viewed 3,477 times
0
Eitan T
- 32,342
- 13
- 69
- 107
Michael Frey
- 898
- 2
- 14
- 34
-
You could do this with regular expressions: http://www.regular-expressions.info/. – Felix Kling May 28 '12 at 10:51
-
http://stackoverflow.com/questions/834303/php-startswith-and-endswith-functions – bos May 28 '12 at 10:53
-
Or - if the numbers are strings - with `substr`: [substring info](http://www.php.net/manual/en/function.substr.php) – Tikkes May 28 '12 at 10:53
-
Maybe the answer that was listed here: http://stackoverflow.com/questions/4979238/php-get-all-keys-from-a-array-that-start-with-a-certain-string – Sandeep Bansal May 28 '12 at 10:54
5 Answers
6
$codes = array(1 => 'US', 20 => 'Egypt');
$phone = '002087458454';
foreach ($codes as $code => $country) {
if (strpos($phone, "00$code") === 0)
break;
}
echo $code; // 20
echo $country; // Egypt
flowfree
- 16,008
- 12
- 48
- 75
-
1You must check for `=== 0` instead of `== 0`. `strpos()` can return `FALSE` (string not found) and `FALSE == 0` is true!!! – Salman A May 28 '12 at 11:22
2
Referring to PHP - get all keys from a array that start with a certain string
foreach ($array as $key => $value) {
if (substr($value, 0, 2) == "00") {
echo "$key\n";
}
}
Community
- 1
- 1
Sandeep Bansal
- 6,166
- 15
- 81
- 122
1
Use regular expressions:
$str ="0041";
if(preg_match('#00[0-9]+#', $str, $array)){
echo substr($array[0], 2);
}
nullpointr
- 514
- 4
- 15
-
-
-
Please note regex may have a performance impact in large data sets. – Jimmy Adaro Feb 01 '18 at 18:11
-1
Use explode function to separate the string in arrays, and you can acess with $string.
j0k
- 22,303
- 28
- 77
- 86
Lucas Reis
- 401
- 2
- 8