1

我有这个小代码来捕获括号之间的文本:

$string = '[title=my title] http://bit.ly/gANFxi [maps:some cool place]';    
preg_match_all('/\[([^\]]*)\]/', $string, $matches);
print_($matches[0]);

我得到的是以下内容:

    大批(
      [0] => [标题=我的标题]
      [1] => [地图:一些很酷的地方]
    )

我想更严格地避免“[some-not cool]”或“[another+stuff]”,所以我只需要捕获 [some:thing] 和 [some=thing]。

我该怎么做?

4

2 回答 2

2

这将捕获包含 '=' 或 ':' 的所有内容并忽略其他内容:

$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]" 但应该这样吗?(注意多个单词以及 '=' 和 ':')。

于 2011-11-28T00:58:06.867 回答
1

如果冒号或等号之前的部分应仅由字母组成,则可以使用以下代码:

preg_match_all('/\[([a-z]+[:=][^\]]+)\]/i', $string, $matches);

如果第一部分更类似于 PHP 标识符(除了$),那么您可以使用以下代码:

preg_match_all('/\[([a-z_]+[a-z0-9_]+[:=][^\]]+)\]/i', $string, $matches);
于 2011-11-28T01:10:58.657 回答