I need to put a string like user-profile/id=3 into regex form. I tried 'user-profile/id=\d+$' and also 'user-profile/([a-z][.][0-9]+)/?$', but none of them are working. What is the correct way?
3 Answers
Since your string is always in the format as above, you do not need a regex. Use a mere explode:
explode("/", $s)[1]
See this demo.
Another non-regex approach: use strstr to get the substring after and including /, and then get the substring from the 1 char:
substr(strstr($s, "/"),1);
See another PHP demo
Comments
Your problem is that you aren't escaping the / character with a backslash.
Another problem you could face immediately after solving that one, is that you are using the $ character, which means end of line. If there are more characters afterwards, even just a single space, then it won't match.
If you try:
user-profile\/(id=\d+)
You'll probably find that it matches just fine. The brackets I added in will capture id=3 in capture group #1.
1 Comment
/ in a regex. Try '~user-profile/(id=\d+)~'If you just want to extract id=3 I recommend to use preg_replace. Like:
$str = 'user-profile/id=3';
$after_preg = preg_replace('/user-profile\//', '', $str);
echo $after_preg;
If you want to get just a number it can be as follows:
$str = 'user-profile/id=3';
$after_preg = preg_replace('/user-profile\/id=/', '', $str);
echo $after_preg;
More about it you can read in PHP Manual: preg_replace
If you want to check if you string is like user-profile/id=3 you can use regex:
user-profile\/id=\d*
id=3part.explode("/", $s)[1]approach? I have an impression your string is always in the format as above, you do not need a regex. See ideone.com/2QFYks