Reputation: 5232
Can someone tell me how to get "123" out of this string with regex:
.../groups/123_abc/...
I am sure that
/groups/
is unique in that string.
Upvotes: 0
Views: 161
Reputation: 48011
Unnecessarily using lookarounds in a regex pattern can lead to poor performance.
This task does not require any lookarounds. Match the leading, literal /groups/
subsrtring, then release it from the full string match using \K
, then match the desired digits.
Code: (Demo)
$str = '.../groups/123_abc/...';
var_export(
preg_match('#/groups/\K\d+#', $str, $m)
? $m[0]
: null
);
If you use explode()
as an alternative to the above script, you will need to remove the unwanted characters from element [1]
using a second technique.
Upvotes: 0
Reputation: 67988
(?<=groups\/)\d+
Try this.See demo.
https://regex101.com/r/sJ9gM7/57
$re = "/(?<=groups\\/)\\d+/im";
$str = ".../groups/123_abc/...";
preg_match_all($re, $str, $matches);
Upvotes: 1
Reputation: 59282
Whatever may be the language, you can split on "/groups/"
and then take the second element, which is at index 1.
Then split on _
and take the first element which is at index 0
.
Upvotes: 2