AKKAweb
AKKAweb

Reputation: 3807

REGEX: Extract parameter from URL

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,

Upvotes: 0

Views: 2106

Answers (2)

Kai Sternad
Kai Sternad

Reputation: 22830

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

Upvotes: 1

TerryE
TerryE

Reputation: 10888

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 :-)

Upvotes: 1

Related Questions