Jump to content

Capturing Part Of URL


Hate

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/261061-capturing-part-of-url/
Share on other sites

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>';
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.