preg_replace 还是 preg_replace_callback?
我在一些使用旧系统的页面上有链接,例如:
<a href='/app/?query=stuff_is_here'>This is a link</a>
它们需要转换为新系统,就像:
<a href='/newapp/?q=stuff+is+here'>This is a link</a>
我可以使用 preg_replace t0 更改我需要的一些内容,但我还需要替换查询中的下划线用 + 代替。我当前的代码是:
//$content is the page html
$content = preg_replace('#(href)="http://www.site.com/app/?query=([^:"]*)(?:")#','$1="http://www.site.com/newapp/?q=$2"',$content);
我想做的是在 $2 变量上运行 str_replace ,所以我尝试使用 preg_replace_callback ,但永远无法让它工作。我应该怎么办?
I have links on some pages that use an old system such as:
<a href='/app/?query=stuff_is_here'>This is a link</a>
They need to be converted to the new system which is like:
<a href='/newapp/?q=stuff+is+here'>This is a link</a>
I can use preg_replace t0 change some of what i need to, but i also need to replace underscores in the query with +'s instead. My current code is:
//$content is the page html
$content = preg_replace('#(href)="http://www.site.com/app/?query=([^:"]*)(?:")#','$1="http://www.site.com/newapp/?q=$2"',$content);
What I want to do is run str_replace on the $2 variable, so I tried using preg_replace_callback, and could never get it to work. What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须传递有效的 回调 [docs] 作为第二个参数:函数名称、匿名函数等。
这是一个示例:
或者使用 PHP 5.3:
您可能还想尝试使用HTML 解析器而不是正则表达式:如何在 PHP 中解析和处理 HTML/XML?
You have to pass a valid callback [docs] as second parameter: a function name, an anonymous function, etc.
Here is an example:
Or with PHP 5.3:
You may also want to try with a HTML parser instead of a regex: How do you parse and process HTML/XML in PHP?
使用 dom 解析文档,搜索所有“a”标签然后替换可能是一个好方法。有人已经评论了向您发布此链接来向您展示正则表达式并不总是处理 html 的最佳方式。
无论如何,这段代码应该可以工作:
请注意,我使用 preg_replace 执行此操作,但这可以使用 str_ireplace 或 str_replace
Parsing your document with dom, searching for all "a" tags and then replacing could be a good way. Someone already commented posting you this link to show you that regex isn't always the best way to work with html.
Ayways this code should work:
Notice that i did this with preg_replace but this can be done with str_ireplace or str_replace
或者您可以简单地使用 preg_match() 并收集匹配的字符串。然后将 str_replace() 应用于其中一个匹配项,并将“+”替换为“_”。
Or you can use simply preg_match() and collect matched strings. Then apply str_replace() to one of the matches and replace "+" to "_".
将数组传递给
preg_replace
作为模式和替换:Pass arrays to
preg_replace
as pattern and replacement: