Reputation: 1467
I am trying to get ONLY the numbers between the two brackets ([ ]) out of the string.
Here is my code:
$str = "[#123456] Some text";
preg_match('/^[#(?P<number>\w+)]/', $string, $matches);
// Returns 123456
echo $matches['number'];
Anyone able to help me out with this?
EDIT: I cleared up my question. I need to get ONLY the numbers between the brackets. The responses so far will give me numbers in the whole string.
Upvotes: 1
Views: 171
Reputation: 3763
If you need the numbers as well as the braces around them, you can use this regex:
preg_match('/\[#\d+\]/U', $str, $matches);
echo $matches[0];
Otherwise, use
preg_match('/\[#(\d+)\]/U', $str, $matches);
echo $matches[1];
Upvotes: 2
Reputation: 2256
This will return numbers only from within this context [#....]
$str = "[#123456] Some text";
preg_match('/\[#(\d+)\]/', $str, $matches);
var_dump($matches);
echo $matches[1]; // 123456
Upvotes: 0
Reputation: 5121
Or...(edited for code to be displayed as code)
$str = preg_replace('/[^0-9]/', '', $str);
Upvotes: 0
Reputation: 7040
Use this:
preg_match('/[0-9]*/', $string, $matches);
var_dump($matches);
For more info on regular expressions, click here
Upvotes: 0