Reputation: 21
I have a string that contains a name followed by a town. So like John Smith Smithville
.
I need to separate this out into two variables (name
, town
) or an array.
I have an array of town names to check against. Whats the best way to separate the string into two once the town name is found in the string?
$string = "John Smith Smithville";
$townlist = array("smithville", "janeville", "placeville");
if(contains($string,$townlist))
{
//separate into two variables
}
Upvotes: 2
Views: 329
Reputation: 490233
This uses regex to do it.
/
in them, or we can't use array_map()
(preg_quote()
's 2nd argument is the delimiter).|
.$matches
will have name as 1
and and town as 2
indexes.$string = 'John Smith Smithville';
$townlist = array('smithville', 'janeville', 'placeville');
if (preg_match_all(
'/^(.*)\s(' . implode('|', array_map('preg_quote', $townlist)) . ')$/i',
$string,
$matches
))
{
var_dump($matches);
}
array(3) {
[0]=>
array(1) {
[0]=>
string(21) "John Smith Smithville"
}
[1]=>
array(1) {
[0]=>
string(10) "John Smith"
}
[2]=>
array(1) {
[0]=>
string(10) "Smithville"
}
}
Upvotes: 6
Reputation: 69991
This does the trick I think
Should work, did a few tests.
$string = "John Smith Smithville";
$townlist = array("smithville", "janeville", "placeville");
function stringSeperation($string, $list)
{
$result = array();
foreach($list as $item)
{
$pos = strrpos(strtolower($string), strtolower($item));
if($pos !== false)
{
$result = array(trim(substr($string, 0, $pos)), trim(substr($string, $pos)));
break;
}
}
return $result;
}
var_dump(stringSeperation($string, $townlist));
Upvotes: 1
Reputation: 10848
Have you think about "special cases", such as: "John Smith New York"? or "New York New York" (the name can contains space, and person name can be the same with the city)
I think that the more approriate solution is: for every string str, we check with all the city name. The check procedure is (pseudo code):
foreach str in strArray[]
foreach city in cities
tmp = Get the substring in the end of str, which equal the length of the "city"
if (tmp == city) then {name = substring(str, 0, strlen(str) - strlen(tmp)); break;}
Upvotes: 0