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
Share on other sites

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
}

Link to comment
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>';
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.