使用preg_match php在[]之间提取数据

时间:2014-07-24 09:04:55

标签: php regex

我尝试仅从我的响应文本文件中提取[]之间的数字:

$res1 = "MESSAGE_RESOURCE_CREATED Resource [realestate] with id [75739528] has been created.";

我使用此代码

$regex = '/\[(.*)\]/s';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[1];

我的结果是:

realestate] with id [75742084

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

使用此:

$regex = '~\[\K\d+~';
if (preg_match($regex, $res1 , $m)) {
    $thematch = $m[0];
    // matches 75739528
    } 

the Regex Demo 中查看匹配。

<强>解释

  • \[与左括号匹配
  • \K告诉引擎放弃与其返回的最终匹配项目匹配的内容
  • \d+匹配一个或多个数字

答案 1 :(得分:0)

你的正则表达式是,

(?<=\[)\d+(?=\])

DEMO

PHP代码将是,

$regex = '~(?<=\[)\d+(?=\])~';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[0];

输出:

75739528

答案 2 :(得分:0)

我假设您想要匹配括号内的内容,这意味着您必须匹配除结束括号外的所有内容:

/\[([^]]+)\]/g

<强> DEMO HERE

忽略preg_match()中的g-flag:

$regex = '/\[([^]]+)\]/';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[1]; //will output realestate
echo $matches_arr[2]; //will output 75739528
相关问题