我有一串这样的数据。
$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的代码后这是一个问题。
你可以改用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年9月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年9月26日)
您也可以尝试此操作(仅更改以下行以达到您在评论中提到的结果)
$array = preg_split( "/([a-zA-Z]{1,4}'/)/", $str, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
演示。
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);