开发者

How do I break apart a URL to its component parts in PHP?

Regular expressions have never been one of my strong points, and this one has me stumped. As part of a project, I want to develop an SEO link class in PHP. Handling the mod_rewrite through Apache is fairly straightforward for me, and that works great.

However, I'd like to create a 开发者_开发问答function which is able to generate the SEO link based on a dynamic URL I pass in as the first (and only) parameter to the function.

For example, this would be the function call in PHP:

<a href="<?= SEO::CreateLink('blog/post.php?post=123&category=5') ?>" title="Blog Post Title">Blog Post Title</a>

The function CreateLink would then analyse the string passed in, and output something like this:

blog/blog-post-title

The URL stub of the blog post is stored in the Database already. I think the best way to achieve this is to analyse the dynamic URL string passed in, and generate an associative array to be analysed. My question is, what would the Regular Expression be to take the URL and produce the following associative array in PHP?

link_pieces['page_type'] = 'blog/post';
link_pieces['post'] = 123;
link_pieces['category'] = 5;

Where page_type is the base directory and request page without extension, and the other array values are the request vars?


You can just use parse_url and parse_str, no need for regexes.


Use parse_url to break the URL into parts:

This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

Then use parse_str to break down the querystring part of the URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜