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
andparse_str
, no need for regexes.Use
parse_url
to break the URL into parts:Then use
parse_str
to break down the querystring part of the URL.