0

I have strings containing this (where the number are integers representing the user id)

  @[calbert](3)
  @[username](684684)

I figured I need the following to get the username and user id

   \((.*?)\) 

and

   \[(.*?)])

But is there a way to get both at once?

And PHP returns, is it possible to only get the result without the parenthesis (and brackets in the username case)

  Array
    (
[0] => (3)
[1] => 3
     )
1

2 Answers 2

3
\[([^\]]*)\]|\(([^)]*)\)

Try this. You need to use | or operator. This provides regex engine to provide alternating capturing group if the first one fails.

https://regex101.com/r/tX2bH4/31

$re = "/\\[([^\\]]*)\\]|\\(([^)]*)\\)/im";
$str = " @[calbert](3)\n @[username](684684)";
 
preg_match_all($re, $str, $matches);

Or you can use your own regex. \((.*?)\)|\[(.*?)\])

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

Comments

0

Through positive lookbehind and lookahead assertion.

(?<=\[)[^\]]*(?=])|(?<=\()\d+(?=\))
  • (?<=\[) Asserts that the match must be preceeded by [ character,

  • [^\]]* matches any char but not of ] zero or more times.

  • (?=]) Asserts that the match must be followed by ] symbol.

  • | Called logical OR operator used to combine two regexes.

DEMO

1 Comment

How to only get numbers because is the string is @[leesfer](3) (not that), "not that" is a match ??

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.