Raphael Marco
Raphael Marco

Reputation: 494

PHP Regex extract numbers inside brackets

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

Upvotes: 3

Views: 3539

Answers (2)

Sam
Sam

Reputation: 20486

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.

Upvotes: 6

Sharanya Dutta
Sharanya Dutta

Reputation: 4021

Use the preg_match_all function in PHP if you’d like to produce the behaviour of the g modifier in Javascript. Use the preg_match function otherwise.

preg_match_all("/@\\[([0-9]+)\\]/", $example_message, $matches);

Explanation:
/ opening delimiter
@ match the at sign
\\[ match the opening square bracket (metacharacter, so needs to be escaped)
( start capturing
[0-9] match a digit
+ match the previous once or more
) stop capturing
\\] match the closing square bracket (metacharacter, so needs to be escaped)
/ closing delimiter

Now $matches[1] contains all the numbers inside the square brackets.

Upvotes: 3

Related Questions