gpt4 book ai didi

php - Preg_replace 还是 preg_replace_callback?

转载 作者:可可西里 更新时间:2023-11-01 00:36:05 24 4
gpt4 key购买 nike

我在一些使用旧系统的页面上有链接,例如:

<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,但永远无法让它工作。我该怎么办?

最佳答案

您必须传递一个有效的 callback [docs]作为第二个参数:函数名、匿名函数等。

这是一个例子:

function my_replace_callback($match) {
$q = str_replace('_', '+', $match[2]);
return $match[1] . '="http://www.site.com/newapp/?q=' . $q;
}
$content = preg_replace_callback('#(href)="http://www.site.com/app/?query=([^:"]*)(?:")#', 'my_replace_callback', $content);

或者使用 PHP 5.3:

$content = preg_replace_callback('#(href)="http://www.site.com/app/?query=([^:"]*)(?:")#', function($match) {
$q = str_replace('_', '+', $match[2]);
return $match[1] . '="http://www.site.com/newapp/?q=' . $q;
}, $content);

您可能还想尝试使用 HTML 解析器而不是正则表达式:How do you parse and process HTML/XML in PHP?

关于php - Preg_replace 还是 preg_replace_callback?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com