
|
View Full Version : Php code to separate text?
acctman 04-06-2010, 08:18 AM I need help with a piece of coding that will separate text
with the first separation first word will be after the Comma then always 2 letters followed by a Space the a set of numbers/letters
original text: New York, NY 10011
processed:
New York
NY
10011
this set separate is by a Comma
original text: LONDON, 17
processed:
LONDON
17
TheSimpleHost-Nathan 04-06-2010, 08:33 AM <?php
// input
$text = 'New York, NY 10011';
// split string on comma
$split = explode(',',$text);
// set New York
$part1 = array($split[0]);
// set NY and 10011
$part2 = explode(' ',$split[1]);
// merge array into one
$array = array_merge($part1,$part2);
// print
print_r($array);
?>
This is only a quick piece of code, there are better ways to do it but this works...
mattle 04-06-2010, 11:19 AM preg_match() is your friend.
$text = "New York, NY 10011";
preg_match("/(.*)\,\s+([A-Z]{2})\s+([\d]+)/", $text, $parts);
var_dump($parts);
How to read the regex:
( - start capturing 1st element
.* - matching any characters
) - end capturing 1st element
\, - followed by a comma
\s+ - followed by one or more whitespace characters
( - start capturing 2nd element
[A-Z]{2} - matching exactly 2 capital letters
) - stop capturing 2nd element
\s+ - followed by one or more whitespace characters
( - start capturing 3rd element
[\d]+ - matching one or more digits
) - stop capturing 3rd element
acctman 04-06-2010, 12:15 PM preg_match() is your friend.
$text = "New York, NY 10011";
preg_match("/(.*)\,\s+([A-Z]{2})\s+([\d]+)/", $text, $parts);
var_dump($parts);
How to read the regex:
( - start capturing 1st element
.* - matching any characters
) - end capturing 1st element
\, - followed by a comma
\s+ - followed by one or more whitespace characters
( - start capturing 2nd element
[A-Z]{2} - matching exactly 2 capital letters
) - stop capturing 2nd element
\s+ - followed by one or more whitespace characters
( - start capturing 3rd element
[\d]+ - matching one or more digits
) - stop capturing 3rd element
thanks for all the help.
how would that would for LONDON, 17 the A-Z would need to be A-Z & 0-9 for UK
weboutloud-Chris 04-06-2010, 12:21 PM thanks for all the help.
how would that would for LONDON, 17 the A-Z would need to be A-Z & 0-9 for UK
The 0-9 is what the
[\d]+ - matching one or more digits
Bit is for, I believe. I'm no regex expert, but I'm pretty sure. :)
acctman 04-06-2010, 12:48 PM The 0-9 is what the
Bit is for, I believe. I'm no regex expert, but I'm pretty sure. :)
it has to be a combination of A-z & 0-9 because it could be H9
acctman 04-06-2010, 01:21 PM $uscountry = $_POST['locus'];
preg_match("/(.*)\,\s+([A-Z]{2})\s+([\d]+)/", $uscountry, $parts);
var_dump($parts);
how do I use the var_dump($parts); code to set $city $state $zip.
mattle 04-07-2010, 12:03 PM try this regex instead
/(.*)\,\s+(?:([A-Z]{2})\s)?+([\dA-Z]+)/
To extract the parts, use this:
list($original, $city, $state, $zip) = $matches;
|