0

What REGEX should I use to extract the following parameter from a url string:

/?c=135&a=1341

I basically want to get the value of the a parameter from this string.

Thanks,

2
  • There are two parameters in this url. Which one do you want? Commented Feb 12, 2012 at 16:53
  • As pointed out in my question, I am looking to extract the a value. I have already solved it.. see answer form bunting Commented Feb 12, 2012 at 22:46

2 Answers 2

1

If you want to extract the value of a, and the value consists of one to many digits, this regex should work:

preg_match("/a=(\\d{1,})/ui", $_SERVER['REQUEST_URI'], $matches)

Then use $matches[1] to display the a value

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

3 Comments

I wasnt able to get this working but I was able to find the following solution: preg_match("/\?c=(\w+)\&a=(\w+)/i", $_SERVER['REQUEST_URI'], $matches); Thanks for helping...
Sure, with PHP the above would be: preg_match("/a=(\\d{1,})/ui", $searchText)
PERFECT. This works. Yeah, I should have pointed that out before that I was using PHP. Everything works good now... t
1

I am going to answer a slightly more general Q which is suggested by your ? prefix that you are trying to remove a specific parameter from a URI request string (which drops the leading ?). And in this case using the mod_rewrite engine so that you can implement this in your .htaccess file.

The rule is somewhat more complex because you don't necessarily know where in the query parameters a=XXX comes, so you need different regexps for the case where a is first and a is a subsequent parameter. You do this by ((?=a=)regexp1|regexp2) so here it is:

 RewriteEngine on
 RewriteBase   \
 RewriteCond   %{QUERY_STRING} ^(?(?=a=)a=[^&]*&?(.*)|(.*)&a=[^&]*(&.*)?)
 RewriteRule   ^.*             $0?%1%2%3                        [L]

If a is first the %1 contain rest otherwise %2 and %3 the bookends (%3 may be blank).

If you want this to occur for specific scripts then replace the rule regexp ^.* by a more specific one.

Enjoy :-)

5 Comments

The same regexp will work in a preg_match() but why aren't you just using $_GET ???
I tried the stay away from .htaccess. I tried that before but did not work... maybe something is wrong with my system. I will check...
I note that you still ducked my Q as to why to are editing $_SERVER['REQUEST_URI'] and not just using $_GET :-)
I am not sure how to use _GET in this situation. Can you suggest something for my learning. Thanks
Sure if you want to ignore a variable then just don't use it or unset it -- or are you calling some 3rd-part framework that accesses $_SERVER['REQUEST_URI']

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.