1

I need a way to remove the surrounding square brackets from this using only php:

[txt]text[/txt]

So the result should be: text

They will always occur in matched pairs.

They always will be at the start and end of the string. Thet will always be [txt1][/txt1] or [url2][/url2]

How can i do it?

Joscplan
  • 1,024
  • 2
  • 15
  • 35
  • 1
    Will the square brackets always occur in matched pairs ([thing]...[/thing]?) Will they always be at the start and end of the string? Might they be nested? Might they be improperly nested ([thing1]...[thing2]...[/thing1]...[/thing2])? What should happen if they are? – Hammerite Aug 17 '13 at 16:29
  • @Hammerite Yes, they will always occur in matched pairs. They always will be at the start and end of the string. Thet will always be [thing1][/thing1] or [thing2][/thing2] – Joscplan Aug 17 '13 at 16:35
  • are you looking for a [bbcode parser](http://php.net/bbcode)? If so then possible duplicate of http://stackoverflow.com/questions/7545920 – Gordon Aug 17 '13 at 16:35
  • @Gordon Something like it but I just need this specific part. – Joscplan Aug 17 '13 at 16:38

4 Answers4

1

Try this:

preg_replace("/\[(\/\s*)?txt\d*\]/i", "", "[txt]text[/txt]");

Update:

This will work for "whatever" in the brackets:

preg_replace("/\[.+?\]/i", "", "[txt]text[/txt]");
vee
  • 38,255
  • 7
  • 74
  • 78
  • Yes but this will only work with txt not with what ever is within the brackets. – Joscplan Aug 17 '13 at 16:37
  • How can I make it to work with what ever it is within the brackets? Thanks. – Joscplan Aug 17 '13 at 17:03
  • @JoseCardama, please see the updated answer. That will match and remove whatever is in the brackets. But note that this will also remove any such tags that are not in pairs. – vee Aug 17 '13 at 18:26
0

You can use regex:

$string = '[whatever]content[/whatever]';
$pattern = '/\[[^\[\]]*\]/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);

This will remove all [whatever] from a string.

Sylverdrag
  • 8,898
  • 5
  • 37
  • 54
0

You do not need to use regexp. You can explode the string on first ], after that use the result to explode on [.

Advantage using this method is that it is fast and simple.

Björn3
  • 297
  • 1
  • 2
  • 8
0

If you simply need to get the text between square brackets of a simple structure, then try this:

$str = '[tag1]fdhfjdkf dfhjdkf[/tag1]';
$start_position = strpos($str, ']') + 1;
$end_postion = strrpos($str, '[');
$cleared = substr($str, $start_position, $end_postion - $start_position);

For more complicated structures this code won't work and you'll have to use some other ways.

u_mulder
  • 54,101
  • 5
  • 48
  • 64