I want to split at every ‘;’ and every ‘{‘ from the string below:
// string
$str = 'abc;def;ghi{jkl;}if('mno') {pqr;}';
// expression
$pattern = "/[;{(]/";
$result = preg_split($pattern);
print_r($result);
It splits at the point of every ‘;’ and ‘{‘ but these characters are also removed which I don’t want. I used explode() function though it splits, but also replace that character.
And how to multiple splitting in a string?
expected result should look like that. array (
0 => "abc;",
1 => "def;",
2 => "ghi{",
3 => "jkl;",
4 => "}if('mno') {",
5 => "pqr;",
6 => "}",
)
Please guide me thanks.
Advertisement
Answer
You can use Lookahead and Lookbehind Zero-Length Assertions.
Example:
// string
$str = "abc;def;ghi{jkl;}if('mno') {pqr;}";
// expression
$pattern = "/(?=[;{(])/";
$result = preg_split($pattern, $str);
$result is a array like
array (
0 => "abc",
1 => ";def",
2 => ";ghi",
3 => "{jkl",
4 => ";}if",
5 => "('mno') ",
6 => "{pqr",
7 => ";}",
)