Php matching string

I have an Indian company data set and you need to extract the city and mailbox from the address field:

Example address field: Gowripuram West, Sengunthapuram Post, Near LGB, Karur, Tamilnadu, Karur - 639 002, India

As you can see, the city is Karur, followed by the zip code (hyphen).

I need PHP code to match [city] - [zip]

I don’t know how to do it. I can find Zip after Hypen, but I don’t know how to find the city, please note that City can be 2 words.

Greetings for your time. /

J

+3
source share
6 answers

Regex have their place in all applications, but in different countries / languages ​​you can add unnecessary complexity for micro-levels of processing.

Try the following:

<?php

$str  = "Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";
$res  = substr($str,strpos($str, "," ,3), strpos($str,"\r"));
//this results in " Karur - 639 002, India";

$ruf  = explode($res,"-");
//this results in 
//$ruf[0]="Karur " $ruf[1]="639 002, India";

$city    = $ruf[0];
$zip     = substr($ruf[1],0,strpos($ruf[1], ",");
$country = substr($ruf[1],strpos($ruf[1],","),strpos($ruf[1],"\r"));

?>

. , ~

0

:

<?php
$address = "Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";

// removes spaces between digits.
$address = preg_replace('{(\d)\s+(\d)}','\1\2',$address);

// removes spaces surrounding comma.
$address = preg_replace('{\s*,\s*}',',',$address);
var_dump($address);

// zip is 6 digit number and city is the word(s) appearing betwwen zip and previous comma.
if(preg_match('@.*,(.*?)(\d{6})@',$address,$matches)) {
    $city = trim($matches[1]);
    $zip = trim($matches[2]);
}

$city = preg_replace('{\W+$}','',$city);

var_dump($city);    // prints Karur
var_dump($zip);     // prints 639002

?>
+1

explode , . 2 . ( 2 ), .

$info= explode("-",$adresfieldexample);
0

. , , .

0

regex "Karur" $matches[1] "639 002" $matches[2].

.

$str = "Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";

preg_match( '/.+, (.+) - ([0-9]+ [0-9]+),/', $str, $matches);

print_r($matches);

Regex, , , , , .

0
    $info="Gowripuram West, Sengunthapuram Post, Near L.G.B., Karur, Tamilnadu, Karur - 639 002, India";

$info1=explode("-",$info);

$Hi=explode(",","$info1[1]");

echo $Hi[0];

hopes this will help u.....
0

Source: https://habr.com/ru/post/1735058/


All Articles