简体   繁体   中英

extracting data between [ ] with preg_match php

i try to extract only the number beetween the [] from my response textfile:

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

i use this code

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

my result is:

realestate] with id [75742084

Can someone help me ?

Use this:

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

See the match in the Regex Demo .

Explanation

  • \\[ matches the opening bracket
  • The \\K tells the engine to drop what was matched so far from the final match it returns
  • \\d+ matches one or more digits

Your regex would be,

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

DEMO

PHP code would be,

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

Output:

75739528

I assume you want to match what's inside the brackets, which means that you must match everything but a closing bracket:

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

DEMO HERE

Omit the g-flag in preg_match() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM