preg_replace 在替换中应用字符串函数(如 urlencode)
我想以这种方式解析php中html文档字符串中的所有链接:将href='LINK'替换为href='MY_DOMAIN?URL=LINK',所以因为LINK将是url参数,所以必须对它进行urlencoded。我正在尝试这样做:
preg_replace('/href="(.+)"/', 'href="http://'.$host.'/?url='.urlencode('${1}').'"', $html);
但是 '${1}' 只是字符串文字,而不是在 preg url 中找到,我需要做什么才能使此代码正常工作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,为了回答你的问题,你对正则表达式有两种选择。
您可以使用
e
修饰符到正则表达式,它告诉preg_replace
替换是 php 代码并且应该执行。这通常被认为不太好,因为它实际上并不比 eval 更好...另一个选项(恕我直言,这是更好的)是使用
preg_replace_callback
:但也永远不要忘记,不要用正则表达式解析 HTML...
所以在实践中,更好的方法(更稳健)方式),将是:
Well, to answer your question, you have two choices with Regex.
You can use the
e
modifier to the regex, which tellspreg_replace
that 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:
使用“e”修饰符。
http://uk.php.net/preg-replace - 示例 #4
Use the 'e' modifier.
http://uk.php.net/preg-replace - example #4