Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex extract numbers inside brackets

Tags:

regex

php

I'm currently building a chat system with reply function.

How can I match the numbers inside the '@' symbol and brackets, example: @[123456789]

This one works in JavaScript

/@\[(0-9_)+\]/g

But it doesn't work in PHP as it cannot recognize the /g modifier. So I tried this:

/\@\[[^0-9]\]/

I have the following example code:

$example_message = 'Hi @[123456789] :)';

$msg = preg_replace('/\@\[[^0-9]\]/', '$1', $example_message);

But it doesn't work, it won't capture those numbers inside @[ ]. Any suggestions? Thanks

like image 604
Raphael Marco Avatar asked Jan 22 '26 15:01

Raphael Marco


1 Answers

You have some core problems in your regex, the main one being the ^ that negates your character class. So instead of [^0-9] matching any digit, it matches anything but a digit. Also, the g modifier doesn't exist in PHP (preg_replace() replaces globally and you can use preg_match_all() to match expressions globally).

You'll want to use a regex like /@\[(\d+)\]/ to match (with a group) all of the digits between @[ and ].

To do this globally on a string in PHP, use preg_match_all():

preg_match_all('/@\[(\d+)\]/', 'Hi @[123456789] :)', $matches);
var_dump($matches);

However, your code would be cleaner if you didn't rely on a match group (\d+). Instead you can use "lookarounds" like: (?<=@\[)\d+(?=\]). Also, if you will only have one digit per string, you should use preg_match() not preg_match_all().

Note: I left the example vague and linked to lots of documentation so you can read/learn better. If you have any questions, please ask. Also, if you want a better explanation on the regular expressions used (specifically the second one with lookarounds), let me know and I'll gladly elaborate.

like image 86
Sam Avatar answered Jan 24 '26 08:01

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!