2

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);
2

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I struggled with the bracket after 'slug='['. I could only seem to get it to work as -two- expressions. Obviously I wasn't patient enough in walking it through.
@jchwebdev As you can see there's not a lot of escaping that needs to be done. Once you're comfortable with what needs and doesn't need escaping, your expressions are a lot cleaner. I recommend not using slash (/) as a delimiter, use % or ~ or # depending on the situation. Too many slashes in html: it ends up looking like soup. It's great that you're using NOT (^) in your character classes. You're on your way with regex. :) At this stage you may benefit from "The Elements of Regex Style" article. rexegg.com/regex-style.html
Wow. That is a -great- tutorial. I've looked at many and for some reason this thing just clicked. Many thanks.
0
$test = preg_match('/\[([^\]]+)\]([^\[]+)\[/', '[tooltip slug="test"]Test Text[/tooltip]', $matches);

echo $matches[2];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.