Question

I have a shortcode which I want to be able to strip away depending on the context of the post. Eg.

[tooltip slug="test"]Test Text[/tooltip]

I would like the output to be:

<span class="dummy">Test Text</span>

I have experimented (a lot!) with preg_replace and I can't seem to get it to recognize that the replacement string is between the ']' and then delimited by '[/tooltip]' without doing multiple passes.

Ideas?

Update: As so often happens, about 10 seconds after I wrote this one of my attempts seemed to work. I don't think it's as good as the solution below but FWIW...

$my_var .= preg_replace('/(?:\[tooltip slug=\"([^\"]*)"[^\>]*\]([^\<]*)\[\/tooltip\])/', '<span class="dummy">\\2</span>', $my_post->post_content);
Was it helpful?

Solution

Here is the simple regex you are looking for.

$result = preg_replace('%\[tooltip slug="[^"]*"]([^[]*)\[/tooltip]%',
          '<span class="dummy">\1</span>', $subject);

What we do here is capture the text between the tooltip tags, and insert it in the replacement. Let me know if you need any details.

OTHER TIPS

$test = preg_match('/\[([^\]]+)\]([^\[]+)\[/', '[tooltip slug="test"]Test Text[/tooltip]', $matches);

echo $matches[2];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top