user962449
user962449

Reputation: 3873

how do I match a url in php using regex?

I'm trying to match the value of query v in the following regex:

http:\/\/www\.domain\.com\/videos\/video.php\?.*v=([a-z0-9-_]+)

A sample url:

http://www.domain.com/videos/video.php?v=9Gu0sd2dmm91B9b1

The url is always www and I'm only trying to match the v value. Does anyone know what's wrong with my syntax?

Upvotes: 0

Views: 71

Answers (3)

Sp4cecat
Sp4cecat

Reputation: 991

You are not escaping the period '.' in video.php. I also use a different delimiter if I am escaping paths/URL's - like this:

preg_match( "#http://www\.domain\.code/videos/video\.php\?.*v=([^&]*)#", $url, $matches );

If the v= is in the middle of the query string,

v=([^&]*)

.. will match everything up to another & symbol, just in case characters other than alphas and _,- end up in there for some reason.

Upvotes: 0

Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

you forget the capital letters

http:\/\/www\.domain\.com\/videos\/video.php\?.*v=([a-zA-Z0-9-_]+)

Upvotes: 1

Blender
Blender

Reputation: 298532

Use the parse_url() function. It's way easier to use:

$url_components = parse_url("http://www.domain.com/videos/video.php?v=9Gu0sd2dmm91B9b1");

echo $url_components['query'];

From there I think you can do the rest and slice off the first couple of letters. Once you do that you're left with only the stuff after v=.

Upvotes: 2

Related Questions