根据不同的"关键字拆分字符串"用PHP

时间:2016-11-04 11:03:54

标签: php arrays regex

我在PHP中有一个字符串:

$haystack = "[:something 1]Here is something 1 content[:something 2]here is something else[:something completely different]Here is the completely different content"

它可以永远持续下去。

所以,我需要将它们分成一个关联数组:

$final_array = [
   'something 1' => 'Here is something 1 content',
   'something 2' => 'here is something else',
   'something completely different' => 'Here is the completely different content'
]

唯一设置的是开始[:然后结束]关键字可以是带有空格等的整个句子。

怎么做?

3 个答案:

答案 0 :(得分:0)

试试这个,使用explode

$str = "Hello world. It's a beautiful day.";
$main_array = explode("[:",$haystack);
foreach($main_array as $val)
{
    $temp_array = explode("]",$val);
    $new_array[$temp_array[0]] =  $temp_array[1];
}
print_r(array_filter($new_array));

<强> DEMO

答案 1 :(得分:0)

您需要使用explode来分割您的strig。像这样:

     $haystack = "[:something 1]Here is something 1 content[:something 2]here is something else[:something completely different]Here is the completely different content";

    // Explode by the start delimeter to give us 
    // the key=>value pairs as strings
    $temp = explode('[:', $haystack);
    unset($temp[0]); // Unset the first, empty, value
    $results= []; // Create an array to store our results in

    foreach ($temp as $t) { // Foreach key=>value line
        $line = explode(']', $t); // Explode by the end delimeter
        $results[$line[0]] = end($line); // Add the results to our results array
    }

答案 2 :(得分:0)

怎么样:

$haystack = "[:something 1]Here is something 1 content[:something 2]here is something else[:something completely different]Here is the completely different content";
$arr = preg_split('/\[:(.+?)\]/', $haystack, 0, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$res = array();
for($i = 0; $i < count($arr); $i += 2) {
    $res[$arr[$i]] = $arr[$i+1];
}
print_r($res);

<强>输出:

Array
(
    [something 1] => Here is something 1 content
    [something 2] => here is something else
    [something completely different] => Here is the completely different content
)