我有一个这样的数组:
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
答案 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_all
,array_map
和implode
函数的简单解决方案:
$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)