0

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.

gregpress
  • 143
  • 1
  • 8

1 Answers1

1

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

hwnd
  • 69,796
  • 4
  • 95
  • 132
  • That is awesome and works great, however my regex selects what is inside the brackets, not outside. I am building my regular expression based on shortcode names - this is important because I need to avoid stray brackets. Here is an example with the the regex I am creating. http://regex101.com/r/pR6qP4/2 do you know of a simple way to invert this regex selection? In the sample text I am searching, I am using two of a possible 9 shortcodes. – gregpress Nov 27 '14 at 02:27
  • How would you like to invert the regex, can you provide an example in all that data you posted a link to? – hwnd Nov 27 '14 at 02:29
  • To get your callback working, I need to select all of the data surrounding possible shortocdes. Here is a more simple regex - just searching two shortcodes. http://regex101.com/r/pR6qP4/3 as mentioned I am now looking for a way to select everything except the shortcodes. – gregpress Nov 27 '14 at 02:51
  • works pretty good. It gets tripped up on stray brackets and I am also trying to support nested shortcodes. Been trying to sort it out with limited success. [link](http://regex101.com/r/bT5jL1) – gregpress Nov 27 '14 at 06:04