I want to split a string with preg_split and surround the results

823 views Asked by At

I am trying to split a string with preg_split, take the results, surround them with custom data, and reinsert them into the original string.

For example:

$string="this is text [shortcode] this is also text [shortcode2] this is text";

Afterwards, I want string to equal:

$string="<span id='0'>this is text </span>[shortcode]<span id='1'> this is also text </span>[shortcode2]<span id='2'>this is text</span>";

I was successful at splitting the string into an array:

$array=preg_split(/\[[^\]]*\]/,$string);

I then tried a for next loop to replace the values - which worked OK, except if the array values had identical matches in the string.

Any help is appreciated - or another approach that might be better.

1

There are 1 answers

4
hwnd On

preg_split() is the wrong tool for this, I would suggest using a callback.

Below is an example to get you started in which you can modify it to your needs along the way.

$str = preg_replace_callback('~(?:\[[^]]*])?\K[^[\]]+~', 
     function($m) { 
        static $id = 0;                                
        return "<span id='".$id++."'>$m[0]</span>"; 
     }, $str);

eval.in demo