Reputation: 121
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
Reputation: 174766
Your regex would be,
(?<=\[)\d+(?=\])
PHP code would be,
$regex = '~(?<=\[)\d+(?=\])~';
preg_match($regex, $res1, $matches_arr);
echo $matches_arr[0];
Output:
75739528
Upvotes: 0
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
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
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\K
tells the engine to drop what was matched so far from the final match it returns\d+
matches one or more digitsUpvotes: 1