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.
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.
eval.in demo