开发者

regex to parse a URL-type string in PHP

开发者 https://www.devze.com 2022-12-22 23:39 出处:网络
I have a string like so: http://www.youtube.com/v/Nnp82q3b844&hl=en_US&开发者_如何学Camp;fs=1&

I have a string like so:

http://www.youtube.com/v/Nnp82q3b844&hl=en_US&开发者_如何学Camp;fs=1&

and I want to extract the

Nnp82q3b844

part of it i.e. the part between /v/ and the first &.

Is there and easy way to do this in PHP?


You don't necessary need regular expressions in this case, you can use the parse_url function to do the work.

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

The above example will output:

Array
(
   [scheme] => http
   [host] => hostname
   [user] => username
   [pass] => password
   [path] => /path
   [query] => arg=value
   [fragment] => anchor
)
/path


yes he shouldn't be too hard take a look here for you reference or to understand my answer

after for the regular expression

something like this should make it

preg_match('|http://www.youtube.com/v/([^&]+)&hl=en_US&fs=1&|', $url, $match );
var_dump($match[1]);

The [^&]+ means basically more than or one character that is not a '&', '[]' define some character possibilities [^] make it reverse so any character not in the bracket, + mean 1 or more character.

But you have better to look it by yourself!

I really advise you to take a good look at regular expressions because it can really save you hours of work and once you get how it works, it is really useful!


$str="http://www.youtube.com/v/Nnp82q3b844&hl=en_US&fs=1&";
$s = parse_url($str);
$t = explode("/", $s["path"]);
print preg_replace("/&.*/","",end($t));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号