0

I have a string that i want to split it to array with

delimiter. But i don't want to lose these delimiters and i want them to be a part of array.

my string is something like below:

$str = "<h3>hello</h3>this is my test and <h3><span>bye</span></h3>";

and what i want to reach is this:

array(
    '<h3>hello</h3>',
    'this is my test and ',
    '<h3><span>bye</span></h3>'
);
enter code here

is there any way to do it?

thanks for your help in advance.

Reza
  • 75
  • 5

1 Answers1

4

You can use preg_split with the PREG_SPLIT_DELIM_CAPTURE option:

$arr = preg_split('/(<h3>.*?<\/h3>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

You will probably want to also include the PREG_SPLIT_NO_EMPTY option so that you don't get empty values when two <h3> blocks are next to each other or at the start or end of the string i.e.

$arr = preg_split('/(<h3>.*?<\/h3>)/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95