user2083524
user2083524

Reputation: 121

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 ?

Upvotes: 0

Views: 65

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174766

Your regex would be,

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

DEMO

PHP code would be,

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

Output:

75739528

Upvotes: 0

rdiz
rdiz

Reputation: 6176

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

Upvotes: 0

zx81
zx81

Reputation: 41838

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

Upvotes: 1

Related Questions