How do I break apart a URL to its component parts

2019-08-01 05:06发布

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?

标签: php url
2条回答
乱世女痞
2楼-- · 2019-08-01 05:34

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

查看更多
唯我独甜
3楼-- · 2019-08-01 05:43

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.

查看更多
登录 后发表回答