如何使用PHP删除周围的Square Brackets

时间:2022-09-15 16:05:37

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

我需要一种方法,只使用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]

它们总是位于字符串的开头和结尾。它总是[txt1] [/ txt1]或[url2] [/ url2]

How can i do it?

我该怎么做?

4 个解决方案

#1


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.

使用这种方法的优点是它快速而简单。

#2


0  

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]");

#3


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.

对于更复杂的结构,此代码不起作用,您将不得不使用其他一些方法。

#4


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.

这将删除字符串中的所有[无论]。

#1


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.

使用这种方法的优点是它快速而简单。

#2


0  

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]");

#3


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.

对于更复杂的结构,此代码不起作用,您将不得不使用其他一些方法。

#4


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.

这将删除字符串中的所有[无论]。