简体   繁体   中英

preg_match() regex pattern for my url

I tried to make a pattern for this url:

http://media.network.com/flv/ea03addc753ff8d80f6be4b49a414cfd/4f3d2012/5016.flv

I just want to retrive the numbers 5016 - fileid from the url.. so i used this code

preg_match( '#http://media\.gilmanetwork\.com/flv/([A-Za-z0-9]+)/([A-Za-z0-9]+)/([A-Za-z0-9]+)\.flv#', $markup, $matches );

so if i use $matches[3] , I should get the number 5016 right?

You've got a big mistake there. gilmanetwork versus network . Try

'#http://media.network.com/flv/([A-Za-z0-9]+)/([A-Za-z0-9]+)/([A-Za-z0-9]+)\.flv#'

Which results in

<?php
$markup = "http://media.network.com/flv/ea03addc753ff8d80f6be4b49a414cfd/4f3d2012/5016.flv";
preg_match( '#http://media.network.com/flv/([A-Za-z0-9]+)/([A-Za-z0-9]+)/([A-Za-z0-9]+)\.flv#', $markup, $matches );
print_r($matches);
// Array ( [0] => http://media.network.com/flv/ea03addc753ff8d80f6be4b49a414cfd/4f3d2012/5016.flv [1] => ea03addc753ff8d80f6be4b49a414cfd [2] => 4f3d2012 [3] => 5016 ) 

Take a look at parse_url() , combined with pathinfo() :

$url      = 'http://media.network.com/flv/ea03addc753ff8d80f6be4b49a414cfd/4f3d2012/5016.flv';
$filename = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);

echo $filename;  // 5016

This approach has an advantage over regular expressions in that the format of the URL can change - and potentially pretty extensively – but so long as the filename of the resource is its ID number, this code will always produce the correct result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM