i want to parse all links in html document string in php in such way: replace href=’LINK’ to href=’MY_DOMAIN?URL=LINK’, so because LINK will be url parameter it must be urlencoded. i’m trying to do so:
preg_replace('/href="(.+)"/', 'href="http://'.$host.'/?url='.urlencode('${1}').'"', $html);
but ‘${1}’ is just string literal, not founded in preg url, what need i do, to make this code working?
Well, to answer your question, you have two choices with Regex.
You can use the
emodifier to the regex, which tellspreg_replacethat the replacement is php code and should be executed. This is typically seen as not great, since it’s really no better than eval…The other option (which is better IMHO) is to use
preg_replace_callback:But also never forget, don’t parse HTML with regex…
So in practice, the better way of doing it (The more robust way), would be: