Skip to content
Advertisement

How to split a string at a specific character but not replace that character?

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 => ";}",
)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement