Created
March 3, 2010 23:11
-
-
Save xdissent/321173 to your computer and use it in GitHub Desktop.
Add GET params to links in HTML.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Filters HTML adding URL parameters to links beginning with a base URL. | |
* | |
* The HTML source code is parsed with a regex replacement which updates the | |
* "href" attribute of all links whose URL begins with the base URL, adding | |
* the given data to the URL in the form of GET parameters. | |
* | |
* Glossary: | |
* | |
* parametize | |
* A fake term describing the action of adding parameters to something. | |
* | |
* @param string $html The HTML source to filter. | |
* @param string $base_url The base URL to determine which links are filtered. | |
* @param array $data An array mapping added parameter names to values. | |
* | |
* @return string | |
*/ | |
function parametize_links($html, $base_url, $data) | |
{ | |
$url = preg_quote($base_url, '/'); | |
$re = '/ | |
( # Capture... | |
<a[^>]* # The a tag and all attributes until... | |
href="' . $url . ' # The href attribute with the base URL | |
[^"?]* # More URL until a question mark or quote | |
) # End the capture leaving off... | |
[?]? # The question mark maybe (but not a quote) | |
/x'; | |
$sub = sprintf('\1?%s&', http_build_query($data)); | |
return preg_replace($re, $sub, $html); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment