Using PHP to split a URL
I am creating a PHP proxy where it accepts a url and confirms it is on my list of servers.
When importing the url from th开发者_StackOverflow中文版e application i ran it to an issue where i needed 2 parser tags. i need it to split along a "\?" tag as well as a string, in my case, "export?"
i am using preg for the first tag. Does this accept the strings like my export tag or is there some other method for doing this?
please le me know how this is accomplished or if you have more questions.
As ircmaxell has already stated in the comments, PHP does already have a function to parse a URL: parse_url
.
And when you have the URL path (I assume your export?
the path suffix plus the query indicator), you can use explode
to split the path into its path segments:
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', $path);
You can then get the last path segment with one of the following:
end($segments)
$segments[count($segments)-1]
And to cope with trailing slashes, you can use rtrim($path, '/')
to remove them.
All together:
$url = 'http://www.example.com/subfolders/export?';
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', rtrim($path, '/'));
echo end($segments);
A regular expression should do the trick, something like the below would work. This is what Django uses in their URL dispatcher
r'^export/$'
Regular expressions are strings matches that may also include variable matches. Because ?
is included within ?
, you have to do your split twice. Once on export?
first, and a second pass on each of those with ?
as your delimiter. As written below, you're just splitting on either of two different strings.
$first = preg_split('export\?', ...);
for ($first) {
array_push ($second,preg_split('\?', ...)');
}
That isn't perfectly valid PHP, but I hope it is close enough pseudocode.
Hey guys i ended up using an explode which looked for the string (export?) and then i used the preg split command to search for the \?. this provided me with the protion i was looking for. thanks guys.
精彩评论