从PHP中的数组值搜索和返回匹配的子字符串

时间:2016-03-18 22:17:41

标签: php arrays

我有一个这样的数组:

0 => dsadjdasActionsdadas | 123 4Dramdsadsa
1 => dsakjdsa Crime dasdsadas Sci-Fci
2 => dasjhdashkAdventuredsadsasa

我想修剪除“Action”,“Dram”,“Crime”,“Sci-Fci”,“Adventure”和“|”之外的所有内容,将数组的键值更改为类似的内容。它必须区分大小写。

0 => Action | Dram
1 => Crime | Sci-Fci
2 => Adventure

2 个答案:

答案 0 :(得分:0)

我希望这有助于你

$array = array("dsadjdasActionsdadas | 123 4Dramdsadsa", "dsakjdsa Crime | dasdsadas Sci-Fci", "dasjhdashkAdventuredsadsasa");
print_r($array);
$clean_array = array_map('cleanGenre', $array);
print_r($clean_array);

function cleanGenre($text)
{
    $genres = array('Action', 'Adventure', 'Crime', 'Dram', 'Sci-Fci');
    $parts = explode("|", $text);
    $result = array();
    foreach($parts as $part)
        foreach($genres as $genre)
            if (preg_match("/". $genre. "/i", $part))
                $result[] = $genre;
    return (implode(' | ', $result));
}

结果将是:

Array
(
    [0] => dsadjdasActionsdadas | 123 4Dramdsadsa
    [1] => dsakjdsa Crime | dasdsadas Sci-Fci
    [2] => dasjhdashkAdventuredsadsasa
)
Array
(
    [0] => Action | Dram
    [1] => Crime | Sci-Fci
    [2] => Adventure
)

请注意我已插入“|” $ array [1]

中的符号

这是我的第一篇文章!

答案 1 :(得分:0)

使用preg_match_allarray_mapimplode函数的简单解决方案:

$arr = [
    0 => 'dsadjdasActionsdadas | 123 4Dramdsadsa',
    1 => 'dsakjdsa Crime dasdsadas |Sci-Fci',
    2 => 'dasjhdashkAdventuredsadsasa'
];

$result = array_map(function($v){
    preg_match_all("/(Action|Dram|Crime|Sci-Fci|Adventure|\|)+?/", $v, $matches);
    return implode(' ',$matches[0]);
}, $arr);


var_dump($result);
// the output:
array (size=3)
  0 => string 'Action | Dram' (length=13)
  1 => string 'Crime | Sci-Fci' (length=15)
  2 => string 'Adventure' (length=9)