Extract 2 numbers out of string between [ ] brackets

I have a string that may contain 2 numbers in brackets
eg.
$string = "this is a string[40] and there may or may not be another [10] in brackets";

i need to get

$a = 40;
$b= 10;

There may often only be one number , sometimes 2.
samkayAsked:
Who is Participating?
 
Roger BaklundConnect With a Mentor Commented:
Try this:
<?php
 
$string = "this is a string[40] and there may or may not be another [10] in brackets";
preg_match_all('/\[([\d]+)\]/',$string,$matches);
if(count($matches[1])>0) $a = $matches[1][0];
if(count($matches[1])>1) $b = $matches[1][1];
echo 'a='.$a.' b='.$b;
 
?>

Open in new window

0
 
samkayAuthor Commented:
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.