使用preg_replace()格式化链接url时出错


Error using preg_replace() to format link url

我有一个多链接:

http://test.com/?sort=newest&v=list&paged=2
http://test.com/?paged=2&sort=newest&v=list

和代码php:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$actual_link = preg_replace("&paged=/'D/", "", $actual_link);
$actual_link = preg_replace("?paged=/'D/", "", $actual_link);

结果错误Warning: preg_replace(): No ending delimiter '&' found ...

如何删除?page =xx和&page =xx

正则表达式必须以符号/开始和结束,例如:preg_replace("/和分页= ' D/", " ", actual_link美元);。你还必须更正变量$actual_link:美元actual_link = " http://{$ _SERVER [' HTTP_HOST ']} {$ _SERVER [' REQUEST_URI ']}";没有引号会抛出错误

试试这个:

preg_replace("/[&?]paged='d/", "", $actual_link);

这就是你想要的:(注意d后面的+,如果有很多数字)

 $link = preg_replace('/[&?]paged='d+/', '', $link);

不过,去掉&这样http://test.com/?paged=2&sort=newest&v=list就不会变成http://test.com/&sort=newest&v=list(我们有一个没用的&之前那种)

,最后是可选的。我们可以像这样删除它:

$link = preg_replace('/[&?]paged='d+[&]?/', '', $link);

最后,您确定要删除?一开始。也许你在排序前需要它?所以http://test.com/?paged=2&sort=newest&v=list不会变成http://test.com/sort=newest&v=list,而是http://test.com/?sort=newest&v=list

在这种情况下,我们使用&可选,不要删除?.

$link = preg_replace('/[&]?paged='d+[&]?/', '', $link);

明智地选择你的毒药

试试这个技巧

$actual_link = "http://test.com/?sort=newest&v=list&paged=2";
$actual_link = preg_replace("/[&?]paged='d/", "&paged=", $actual_link);
echo $actual_link;

演示http://sandbox.onlinephpfunctions.com/code/f4d8392f4948513f8b0682081e717017eb40dea3