有人可以解释如何使用php preg_match
将字符串分解为数组,从字符串的开头到第一个反斜杠?
我有一个数组:
(
[0] => s00473276\Soul To Squeeze\Red Hot Chili Peppers
[1] => t00034422\Soul To Squeeze\Red Hot Chili Peppers
[2] => 209676\Soul To Squeeze\Red Hot Chili Peppers
[3] => s00473331\What Is Soul ?\Red Hot Chili Peppers
[4] => 209672\Show Me Your Soul\Red Hot Chili Peppers
[5] => t00034415\Show Me Your Soul\Red Hot Chili Peppers
[6] => s00473268\Show Me Your Soul\Red Hot Chili Peppers
[7] => s00473233\Out Of Range By Red Hot Chili Peppers\Red Hot Chili Peppers
[8] => 209603\Get On Top\Red Hot Chili Peppers
[9] => t00034374\I've Been Down\Red Hot Chili Peppers
)
我想创建另一个数组,所以我将留下
[0] => s00473276
[1] => t00034422 etc...
答案 0 :(得分:2)
最简单/“最干净”(警告:主观)解决方案可能是array_map()
和explode()
:
<?php
$array = array('s00473276\Soul To Squeeze\Red Hot Chili Peppers',
't00034422\Soul To Squeeze\Red Hot Chili Peppers',
'209676\Soul To Squeeze\Red Hot Chili Peppers',
's00473331\What Is Soul ?\Red Hot Chili Peppers',
'209672\Show Me Your Soul\Red Hot Chili Peppers',
't00034415\Show Me Your Soul\Red Hot Chili Peppers',
's00473268\Show Me Your Soul\Red Hot Chili Peppers',
);
function myFunc($item) {
$parts = explode('\\', $item, 2);
return $parts[0];
}
$newArray = array_map('myFunc', $array);
print_r($newArray);
输出:
Array
(
[0] => s00473276
[1] => t00034422
[2] => 209676
[3] => s00473331
[4] => 209672
[5] => t00034415
[6] => s00473268
)
(demo)
答案 1 :(得分:2)
$new_array = array();
foreach($your_array as $element)
list($new_array[]) = explode('\\', $element);
print_r($new_array);
答案 2 :(得分:2)
为什么preg_match()
?使用substr()
和array_map()
会更快。
array_map('f', $array);
function f($s)
{
return substr($s, 0, strpos($s, '\\'));
}
答案 3 :(得分:1)
你可以这样做:
$arr = array();
foreach($yourArray as $key => $value){
$split = explode('\\', $value);
$arr[$key] = $split[0];
}
print_r($arr);
答案 4 :(得分:0)
尝试:
$input = array( /* your data */ );
$output = array();
foreach ( $input as $value ) {
$output[] = str_split($value, 0, substr($value, '/'));
}
答案 5 :(得分:0)
这是preg_match
$result = array();
foreach ($a as $value) {
preg_match("#([^\\\\]*)\\\\#", $value, $match);
$result[] = $match[1];
}