Hate Posted April 16, 2012 Share Posted April 16, 2012 Hello, I'm trying to capture the red part of the url. The blue part of the URL I would like to be optional. Case should not matter. Should I have the "http://" part a second optional as well? Or should I put it with "www."? Ideally, I just need to ensure that it pulls the video title from that domain regardless of how they accessed the website. What would be the best possible way to achieve this with regex? Summarized: I just need whatever is after /videos/ but would ideally like to ensure that the domain is correct as well. http://www.cooltools.org/videos/how-to-style-menu/ Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/261061-capturing-part-of-url/ Share on other sites More sharing options...
MarPlo Posted April 17, 2012 Share Posted April 17, 2012 Hi, I think this code is good for what you want: $url = 'http://www.cooltools.org/videos/how-to-style-menu/'; if(preg_match('#(http://){0,1}(www.){0,1}cooltools.org/videos/([^/]+)#i', $url, $mc)) { $video = $mc[3]; echo $video; // how-to-style-menu } Quote Link to comment https://forums.phpfreaks.com/topic/261061-capturing-part-of-url/#findComment-1338083 Share on other sites More sharing options...
xyph Posted April 17, 2012 Share Posted April 17, 2012 You don't really need RegEx to do this. Here's a couple methods, one involving a VERY simple RegEx. <?php $url = 'http://www.cooltools.org/videos/how-to-style-menu/'; $parsed = parse_url($url); print_r($parsed); /* returns: Array ( [scheme] => http [host] => www.cooltools.org [path] => /videos/how-to-style-menu/ ) */ $paths = explode( '/', $parsed['path'] ); foreach( $paths as $path ) { if( !empty($path) ) { // ignore empty results from leading/trailing slashes echo '<h3>'.$path.'</h3>'; } } // Alternate method to explode, uses RegEx. Allows empty splits to be ignored automatically $paths = preg_split( '#/#', $parsed['path'], NULL, PREG_SPLIT_NO_EMPTY ); foreach( $paths as $path ) { echo '<h3>'.$path.'</h3>'; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/261061-capturing-part-of-url/#findComment-1338198 Share on other sites More sharing options...
requinix Posted April 17, 2012 Share Posted April 17, 2012 And there's yet another method. Since URLs look kinda like file paths, basename(trim($url, "/")) (Of course this doesn't validate the rest of the URL. Only grabs the last component of the path.) Quote Link to comment https://forums.phpfreaks.com/topic/261061-capturing-part-of-url/#findComment-1338251 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.