preg_split problem

Hello

I have a very long string like this

$test=“fielda: house car random house boat fieldb: house boat snow fieldc: name1 name2 name3 fieldd: test test2 test3 project: one two three”;

I need to echo the string in this way detecting each word followed by ": "

fielda: house car random house boat
fieldb: house boat snow
fieldc: name1 name2 name3
fieldd: test test2 test3
project: one two three

I am using this

$test=“fielda: house car random house boat fieldb: house boat snow fieldc: name1 name2 name3 fieldd: test test2 test3 project: one two three”;

$keywords = preg_split(“/[A-Za-z]+: /”, $test);

foreach($keywords as $value){
echo htmlentities($value).“<br>”;
}

but it return this

house car random house boat
house boat snow
name1 name2 name3
test test2 test3
one two three

instead of this

fielda: house car random house boat
fieldb: house boat snow
fieldc: name1 name2 name3
fieldd: test test2 test3
project: one two three

How can I do it please ? Thank you

From the manual: http://php.net/manual/en/function.preg-split.php

$keywords = preg_split("/([A-Za-z]+: )/", $test, NULL, PREG_SPLIT_DELIM_CAPTURE);

That should capture your delimiter as well, thus producing the output you desire.

Your code captures the delimiter but in another array value

Array ( [0] => [1] => fielda: [2] => house car random house boat [3] => fieldb: [4] => house boat snow [5] => fieldc: [6] => name1 name2 name3 [7] => fieldd: [8] => test test2 test3 [9] => project: [10] => one two three )

could it possible to have this instead ?

Array ( [0] => [1] => fielda: house car random house boat [2] => fieldb: house boat snow [3] => fieldc: name1 name2 name3 [4] => fieldd: test test2 test3 [5] => project: one two three )

Thank you

Aww man, that blows! I’ll have to play with it now. I thought it would work out of the box. Give me some time, I’m sure I can figure something out :smiley:

I don’t particularly like this solution (as it seems hackish), but it works.

<?php
$test="fielda: house car random house boat fieldb: house boat snow fieldc: name1 name2 name3 fieldd: test test2 test3 project: one two three";
$keywords = array_map('implode', array_chunk(preg_split("/([A-Za-z]+: )/", $test, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY), 2));

var_dump($keywords);

Here is what it does:
preg_split: capture the delimiter and ignore empty captures.
array_chunk: take each 2 items in the array and chunk them together (this way the delimiter gets chunked with its phrase)
array_map: send the newly chunked array into implode, so we can glue the delimiter and the phrase together.

And your output using var_dump becomes:

array (size=5)
  0 => string 'fielda: house car random house boat ' (length=36)
  1 => string 'fieldb: house boat snow ' (length=24)
  2 => string 'fieldc: name1 name2 name3 ' (length=26)
  3 => string 'fieldd: test test2 test3 ' (length=25)
  4 => string 'project: one two three' (length=22)

thank you really appreciated !.