Reputation: 1099
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
)
Upvotes: 0
Views: 30
Reputation: 67968
\[([^\]]*)\]|\(([^)]*)\)
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. \((.*?)\)|\[(.*?)\])
Upvotes: 3
Reputation: 174706
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.
Upvotes: 0