how do I parse a url with php
I need to parse a URL in php for a facebook like button. what I do now is this:
<?php
echo curPageURL();
?>
but I have articles that are sometimes 2 or three pages long so I want to parse the url without the page number so that the like button is for the first page of the article. Sometimes a page number does not exist either.
my url looks like this http://www.mydomain.com/23/My-Article-Title/2/
the 2 at the end is the page number indicating page 2. page one of the article appears like this though
http://www.mydomain.com/23/My-Article-Title/
how do I parse the url in php to remove the page number if it exists?
so I wou开发者_开发百科ld only want to parse it if there was a page number.
preg_replace('=\d+/$=', '', $url);
You can use a regular expression with preg_replace:
echo preg_replace('#/[0-9]+(/)?$#', '/', 'http://www.mydomain.com/23/My-Article-Title/34/');
// output: http://www.mydomain.com/23/My-Article-Title/
The above regex removes any /
+ numbers
+ (optional) /
that appears at the end of the URI.
Try to use:
preg_replace('/^(.+[a-zA-Z]\/)[\d]*\/?$/i', '\\1', $str);
$url = 'http://www.mydomain.com/23/My-Article-Title/2/';
$url_info = parse_url($url);
$pathes = (empty($url_info['path']) ? array() : explode('/', trim($url_info['path'], '/')));
if (($len = count($pathes)) > 0 && is_numeric($pathes[$len-1]) )
{
echo "<pre>";
print_r($pathes);
echo "</pre>";
}
?>
精彩评论