PHP Regex,使用preg_match获得多个值

时间:2012-01-23 08:19:14

标签: php regex

我有这个文字字符串:

$text="::tower_unit::7::/tower_unit::<br/>::tower_unit::8::/tower_unit::<br/>::tower_unit::9::/tower_unit::";

现在我想获得7,8和9的值 如何在preg_match_all中做到这一点?

我试过这个:

$pattern="/::tower_unit::(.*)::\/tower_unit::/i";
preg_match($pattern,$text,$matches);

print_r($matches);

但它仍然是错的......

2 个答案:

答案 0 :(得分:5)

你忘了逃避你的模式中的斜线。由于您的模式包含斜杠,因此更容易使用不同的正则表达式分隔符,如评论中所示:

$pattern="@::tower_unit::(\d+)::/tower_unit::@"; 
preg_match_all($pattern,$text,$matches);

我还将(.*)转换为(\d+),如果您要查找的令牌始终是一个数字,那就更好了。另外,如果文本总是较低的,可能会丢失i修饰符。

答案 1 :(得分:0)

你的正则表达式是“贪婪的”。 使用以下

$pattern="#::tower_unit::(.*?)::/tower_unit::#i";

$pattern="#::tower_unit::(.*)::/tower_unit::#iU";

并且,如果您愿意,\ d +而不是。*?或。*

该函数应为preg_match_all