【问题标题】:preg_replace with slash in the endpreg_replace 最后用斜线替换
【发布时间】:2015-10-23 13:52:59
【问题描述】:

得到这个代码

<?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 preg-replace


【解决方案1】:

捕获 () 之间的值并通过 $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,})/", "/$1/", $string);
echo $string;

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

【讨论】:

    【解决方案2】:
    <?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]+)/", "/$1/", $string);
      echo $string;
    ?>
    

    表达式使用capturing group ([0-9]+) 匹配任何整数并捕获其值。然后,它使用/$1/ 作为替代。注意$1 是对组捕获的值的反向引用。

    例如:

    preg_replace("/\?c?page=([0-9]+)/", "/$1/", "page.php?cpage=3");
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 2011-01-24
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      相关资源
      最近更新 更多