Remove WP tag with PHP

Asked

Viewed 54 times

2

Colleagues.

We are creating a new system and removing the WP, but the news will still pick up from the WP, as old news. Only when we bring the column post_content, it brings me the tag that appears next to the image:

[caption id="attachment_9472" align="alignleft" width="350"](here image appears)[/caption]

I tried to use strip_tags, but it didn’t work. We’re taking without using WP, but our own system. How do I remove these tags and leave only the image?

I’m taking it this way:

<?php echo utf8_encode(strip_tags($jmVisualizar->post_content),'[caption]'); ?>

1 answer

5


Using Regex, this is one of the simplest ways:

preg_replace('/\[\/?caption.*\]/U', '', $string )

Basically she changes everything inside [ ] and starts with caption or /caption. The modifier /U serves to catch the smallest possible piece, so that the pope-all .* don’t take things between two different tags.

If you want remove all tags with [ ] the situation may even simplify:

preg_replace('/\[.*\]/U', '', $string );
                           ^--- aqui você põe um espaço se não for para "colar" tudo.

If you need to do something different with the parts before and after the caption:

preg_replace( '/(.*)\[caption.*\](.*)\[\/caption\](.*)/', '$1$2$3', $string );

If you don’t need the outside of the tag, and just want the content:

preg_replace( '/.*\[caption.*\](.*)\[\/caption\].*/', '$1', $string );

If you want remove the tag and content:

preg_replace( '/.*\[caption.*\].*\[\/caption\].*/', '', $string );

See all tests working on IDEONE.


There are a thousand other ways to solve it, it all depends on small details of the variations your data may have.

  • Perfect Bacco, it worked! Thank you very much.

  • 1

    @Fox.11 I usually avoid using Regex for no reason, but in this particular case, it is a very suitable tool to do the job. I’ve left a few examples at IDEONE, so you can see which one pays more for your case, but any questions, let me know.

  • Combined......

Browser other questions tagged

You are not signed in. Login or sign up in order to post.