Php 如何捕捉括号内的文本
我有一个小代码来捕获括号中的文本:Php 如何捕捉括号内的文本,php,regex,brackets,Php,Regex,Brackets,我有一个小代码来捕获括号中的文本: $string = '[title=my title] http://bit.ly/gANFxi [maps:some cool place]'; preg_match_all('/\[([^\]]*)\]/', $string, $matches); print_($matches[0]); 我得到的是: Array( [0] => [title=my title] [1] => [maps:some cool place]
$string = '[title=my title] http://bit.ly/gANFxi [maps:some cool place]';
preg_match_all('/\[([^\]]*)\]/', $string, $matches);
print_($matches[0]);
我得到的是:
Array(
[0] => [title=my title]
[1] => [maps:some cool place]
)
排列(
[0]=>[title=我的标题]
[1] =>[地图:一些很酷的地方]
)
我想做更多的限制,以避免“[一些不酷]”或“[其他+东西]”,
所以我只需要抓住[some:thing]和[some=thing]
如何执行此操作?这将捕获包含“=”或“:”的所有内容,并忽略其他内容:
$string = '[title=my title] http://bit.ly/gANFxi [maps:some cool place] [some-not cool] or [another+stuff]';
preg_match_all('/\\[([^\\]]*[\\=|\\:][^\\]]*)\\]/', $string, $matches);
print_r($matches[0]);
这能奏效吗?还是有进一步的要求?也就是说,这个返回“[some-stuff=some:thing]”但它应该吗?(请注意多个单词以及“=”和“:”)。如果冒号或等号前的部分仅由字母组成,则可以使用以下代码:
preg_match_all('/\[([a-z]+[:=][^\]]+)\]/i', $string, $matches);
preg_match_all('/\[([a-z_]+[a-z0-9_]+[:=][^\]]+)\]/i', $string, $matches);
如果第一部分更类似于PHP标识符(除了$),则可以使用以下代码:
preg_match_all('/\[([a-z]+[:=][^\]]+)\]/i', $string, $matches);
preg_match_all('/\[([a-z_]+[a-z0-9_]+[:=][^\]]+)\]/i', $string, $matches);
世界需要更多的正则表达式experts@AdamSack,世界需要更多的乔姆斯基。