preg_replace 以斜杠结尾

preg_replace with slash in the end

得到这个代码

<?php

$string = "list page.php?cpage=1, list page.php?cpage=2, list page.php?page=3 thats all";
$string = preg_replace("/\?cpage=[0-9]/", "/", $string);
echo $string;
//result 
//list page.php/, list page.php/, list page.php/ thats all
//what i want 
//list page.php/1/, list page.php/2/, list page.php/3/ thats all
?>

有人可以帮忙吗?

演示 https://3v4l.org/LEvph

<?php
  $string = "list page.php?cpage=1, list page.php?cpage=2, list page.php?page=3 thats all";
  $string = preg_replace("/\?c?page=([0-9]+)/", "//", $string);
  echo $string;
?>

表达式使用 capturing group ([0-9]+) 匹配任何整数并捕获其值。然后,它使用 // 作为替代。注意 </code> 是对组捕获的值的反向引用。</p> <p>例如:</p> <pre><code>preg_replace("/\?c?page=([0-9]+)/", "//", "page.php?cpage=3");

捕获第 1 组中的 "3" 并且 // 在替换中被评估为 "/3/"

捕获 () 之间的值并通过 $1 将其投射回来:

$string = "list page.php?cpage=1, list page.php?cpage=2, list page.php?page=3 thats all";
$string = preg_replace("/\?c?page=([0-9]{1,})/", "//", $string);
echo $string;

([0-9]{1,})表示一个或多个数字。 希望这有帮助。