我需要一种方法来删除周围的方括号,只使用php:
[txt]text[/txt]
所以结果应该是:文本
它们总是成对出现。
它们总是在字符串的开始和结束处。t将始终为[txt1][/txt1]或[url2][/ul2]
我该怎么做?
试试这个:
preg_replace("/'[('/'s*)?txt'd*']/i", "", "[txt]text[/txt]");
更新:
这将适用于括号中的"任何":
preg_replace("/'[.+?']/i", "", "[txt]text[/txt]");
您不需要使用regexp。你可以在第一个]上分解字符串,然后使用结果在[.上分解
使用这种方法的优点是快速而简单。
如果您只需要获取简单结构的方括号之间的文本,请尝试以下操作:
$str = '[tag1]fdhfjdkf dfhjdkf[/tag1]';
$start_position = strpos($str, ']') + 1;
$end_postion = strrpos($str, '[');
$cleared = substr($str, $start_position, $end_postion - $start_position);
对于更复杂的结构,此代码将不起作用,您将不得不使用其他一些方法。
您可以使用regex:
$string = '[whatever]content[/whatever]';
$pattern = '/'[[^'[']]*']/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
这将从字符串中删除所有[whatever]
。