我有一串数据。
$str = "abc/text text def/long amount of text ghi/some text"
我有一系列分隔符
$arr = array('abc/', 'def/', 'ghi/', 'jkl/');
我该怎么做才能获得此输出?
Array
(
[abc/] => text text
[def/] => long amount of text
[ghi/] => some text
)
另请注意,$ arr中的所有值可能并不总是出现在$ str中。我刚刚注意到使用下面的@rohitcopyright代码后出现这个问题。
答案 0 :(得分:3)
您可以使用preg_split
代替
$text = "abc/text text def/long amount of text ghi/some text";
$output = preg_split( "/(abc\/|def\/|ghi)/", $text);
var_dump($output);
<强>输出:强>
array(4) {
[0]=>
string(0) ""
[1]=>
string(10) "text text "
[2]=>
string(20) "long amount of text "
[3]=>
string(10) "/some text"
}
更新:(删除空项并重新编制索引)
$output = array_values(array_filter(preg_split( "/(abc\/|def\/|ghi)/", $text)));
var_dump($output);
<强>输出:强>
array(3) {
[0]=>
string(10) "text text "
[1]=>
string(20) "long amount of text "
[2]=>
string(10) "/some text"
}
更新:(2013年第26季度)
$str = "abc/text text def/long amount of text ghi/some text";
$array = preg_split( "/([a-z]{3}\/)/", $str, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$odd = $even = array();
foreach($array as $k => $v)
{
if ($k % 2 == 0) $odd[] = $v;
else $even[] = $v;
}
$output = array_combine($odd, $even);
print_r($output);
<强>输出:强>
Array (
[abc/] => text text
[def/] => long amount of text
[ghi/] => some text
)
更新:(2013年第26季度)
您也可以尝试这一点(仅更改以下行以达到您在评论中提到的结果)
$array = preg_split( "/([a-zA-Z]{1,4}\/)/", $str, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
答案 1 :(得分:0)
Try this you will get the exact output as you want.
$con='abc/text text def/long amount of text ghi/some text';
$newCon = explode('/', $con);
array_shift($newCon);
$arr = array('abc/', 'def/', 'ghi/');
foreach($newCon as $key=>$val){
$newArrStr = str_replace("/", "", $arr[$key+1]);
$newVal = str_replace($newArrStr, "", $newCon[$key]);
$newArray[$arr[$key]] = $newVal;
}
print_r($newArray);