1

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?

7
  • What you want to get from this string with regex? Commented Nov 18, 2016 at 7:12
  • I just want to extract the id=3 part. Commented Nov 18, 2016 at 7:16
  • In that case I hope my answer will help you. Commented Nov 18, 2016 at 7:22
  • 1
    You really do not want a simple 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 Commented Nov 18, 2016 at 7:53
  • 1
    I added 2 non-regex solutions for you. I hope they will be useful. Commented Nov 18, 2016 at 8:02

3 Answers 3

2

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

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

Comments

1

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

It is not necessary to escape / in a regex. Try '~user-profile/(id=\d+)~'
0

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*

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.