3

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

2
  • 4
    Your problem is the ^ in your character class looks for the negative (so [^0-9] looks for anything but a digit). Real answer incoming.... Commented Apr 5, 2014 at 6:05
  • 1
    Also, your JS regex should really be /@\[[0-9_]+\]/g (remove the underscore if there shouldn't be any within the square brackets). Commented Apr 5, 2014 at 6:09

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.