PHP:如何删除“[”和“]”之间的字符串

时间:2013-03-03 15:57:51

标签: php preg-replace

我需要删除[...]内的字符串,包括“[]”本身。我尝试从这个网站搜索解决方案。我有一个线索,我应该尝试使用preg_replace,但它对我来说似乎太专业了。

例如:

[gallery ids="92,93,94,95,96,97,98,99,100" orderby="rand"] Description The thirty-two storey resort condominium in Phuket, located Just 150m from Patong beach where choices of activities, water sp 

我需要从示例文本中删除 [gallery ids =“92,93,94,95,96,97,98,99,100”orderby =“rand”] 。它始终以 [gallery ids =“

开头

请建议。

1 个答案:

答案 0 :(得分:7)

试试这个:

$string = '[gallery ids="92,93,94,95,96,97,98,99,100" orderby="rand"] Description The thirty-two storey resort condominium in Phuket, located Just 150m from Patong beach where choices of activities, water sp ';
$string = preg_replace('/\[gallery ids=[^\]]+\]/', '', $string);

故障:

\[gallery ids=查找以[gallery ids=

开头的子字符串

[^\]]+\]匹配一个或多个不是]的字符,直到您到达]

然后将''取代整个匹配的部分,并且你有新的字符串。