在数组中搜索字符串

时间:2016-06-10 07:48:43

标签: php regex

我正在尝试更改包含数组(城市名称)值的字符串(城市)。

代码:

for ($i=0; $i<$1000; $i++) {

$cities = "I live in Prag";  
$array = array("Wien","Prag","Berlin");
foreach ($array AS $val) {

        if (preg_match("/".$val."/", $cities)) {
        $cities = str_replace($val, ", " . $val. ", ", $cities);    
        }
    }
}

还有另一种解决方案吗?

感谢

3 个答案:

答案 0 :(得分:0)

如果你需要找到符合条件的值的键,那么你需要循环遍历数组,所以像这样使用。

$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
    if(preg_match("/\b$searchword\b/i", $v)) {
        $matches[$k] = $v;
    }
}

答案 1 :(得分:0)

我想......

$cities = "I live in Prag";  
$array = array("Wien","Prag","Berlin");
foreach ($array AS $val) {

    $cities = preg_replace("/(.*)(" . $val . ")(.*)/", "$1, $2, $3", $cities);
}

Echo $cities;

可以做到。

修改工作示例:https://3v4l.org/0eDDW

答案 2 :(得分:0)

以下是使用preg_replaceimplode函数的简单解决方案:

$cities = "I live in Prag but love Wien";
$array = array("Wien","Prag","Berlin");
$cities = preg_replace("/\b". implode("|", $array) ."\b/", ',$0,', $cities);

print_r($cities);  // "I live in ,Prag, but love ,Wien,"