我有一个字符串,其中包含一个名称后跟一个城镇.所以喜欢John Smith Smithville.
我需要将它分成两个变量(name,town)或一个数组.
我有一系列城镇名称要检查.什么是在字符串中找到城镇名称后将字符串分成两个的最佳方法?
$string = "John Smith Smithville";
$townlist = array("smithville", "janeville", "placeville");
if(contains($string,$townlist))
{
//separate into two variables
}
Run Code Online (Sandbox Code Playgroud)
这使用正则表达式来做到这一点.
/,或者我们不能使用array_map()(preg_quote()第二个参数是分隔符).|.$matches会的名称1,并和镇作为2指标.$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);
}
Run Code Online (Sandbox Code Playgroud)
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"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
321 次 |
| 最近记录: |