-3

I have a string in PHP:

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

And it can continue forever.

So, I need to split them into an associative array:

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

The only thing that is set is the beginning [: and then the end ] The keyword can be a whole sentence with spaces etc.

How to do this?

Jimmy Sikh
  • 19
  • 1
  • 6

3 Answers3

0

Try this, use 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));
Xpear
  • 3
  • 2
Dave
  • 3,073
  • 7
  • 20
  • 33
0

You need to use explode to split your strig up. like so:

     $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
    }
Kev Wilson
  • 470
  • 6
  • 19
0

How about:

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

Output:

Array
(
    [something 1] => Here is something 1 content
    [something 2] => here is something else
    [something completely different] => Here is the completely different content
)
Toto
  • 89,455
  • 62
  • 89
  • 125
  • I love everything about this one except for the `.+?` -- I'd rather see a negated character class for performance reasons. – mickmackusa Feb 02 '21 at 06:17