开发者

PHP: Extract string from another

开发者 https://www.devze.com 2023-03-09 20:19 出处:网络
i have some strings (address), all like this: 2 rue lambda, 75018, PARIS I want to get the postal code, in this exemple \"75018\". I\'ve been trying different solution, but i\'m not familiar with

i have some strings (address), all like this:

2 rue lambda, 75018, PARIS

I want to get the postal code, in this exemple "75018". I've been trying different solution, but i'm not familiar with escaped characters , and don't know how to detect coma in the string. Which function should i use to e开发者_如何学运维xtract the postal code?


you can try this:

preg_match('/([0-9]{5})/',$string,$match);
echo $match[1];

This will work whenever there is an address comma separated or simply space separated


If the commas are always there, it is as simple as explode()

$parts = explode(",", "2 rue lambda, 75018, PARIS");
$postcode = trim($parts[1]);


If all your addresses are of France, which has a 5 digit postal code then you can use the following regex to capture it:

\b(\d{5})\b

In PHP you can use it with preg_match as:

$input = '2 rue lambda, 75018, PARIS';
if(preg_match('/\b(\d{5})\b/',$input,$match)) {
   $postal_code = $match[1];
}

Note that this will capture the first 5 digit number in the address. Generally the postal code comes at the end of the address, so we can improve the method by capturing the last 5 digit number in the address by using the regex:

.*\b(\d{5})\b


Is that always the format it will be in? If so you can explode.

$str = '2 rue lambda, 75018, PARIS';
$array = explode(',',$str);
$street = $array[0];
$postal = $array[1];
$city = $array[2];
0

精彩评论

暂无评论...
验证码 换一张
取 消