I've been struggling with this for like half a day already and I can't seem to find the answer. Please do help a noob. :)
I've got a string which consists of few sentences which are in curly brackets. It looks something like this:
{Super duper extra text.} {Awesome another text!} {And here we go again...}
Now I want to split it.
I figured out I could search for patterns like .} {, etc. So I did it like this:
$key = preg_split('/[!?.]{1,3}\} \{/',$key);
But this way I lost the delimiter, I lost all those . ! ? etc. at the end of the sentence.
I tried to do it like that:
$key = preg_split('/([!?.]{1,3}\} \{)/',$key, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = array();
for ($i=0, $n=count($key)-1; $i<$n; $i+=2) {
$sentences[] = $key[$i].$key[$i+1]."<br><br>";
}
But this code never loads, so I gather something's wrong with it. But what?
Thanks in advance.
You don't need to split this, just call preg_match()
on it instead. The matched groups will result in an array. The expression grouped inside ()
, [^}]+
matches all characters up to, but not including, the next }
. The output values you want will be inside the $matches[1]
subarray.
$input = "{Super duper extra text.} {Awesome another text!} {And here we go again...}";
$matches = array();
preg_match_all('/\{([^}]+)\}/', $input, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => {Super duper extra text.}
[1] => {Awesome another text!}
[2] => {And here we go again...}
)
[1] => Array
(
[0] => Super duper extra text.
[1] => Awesome another text!
[2] => And here we go again...
)
)
I doubt you need preg_split()
for this. From what you describe, it sounds like:
$array = explode('} {', trim($string, '{}'));
...will do the job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With