regex 在PHP中基于不同的“关键字”拆分字符串

fcwjkofz  于 2023-04-13  发布在  PHP
关注(0)|答案(3)|浏览(149)

在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'
]

唯一设置的是开始[:,然后是结束]关键字可以是带有空格等的整句。
如何做到这一点?

6psbrbz9

6psbrbz91#

你需要使用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
    }
7d7tgy0s

7d7tgy0s2#

怎么样:

$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
)
pu3pd22g

pu3pd22g3#

试试这个,使用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));

相关问题