singodimejo
singodimejo

Reputation: 13

preg_replace with slash in the end

got this code

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

any one can help?

demo https://3v4l.org/LEvph

Upvotes: 0

Views: 73

Answers (2)

toster-cx
toster-cx

Reputation: 2377

<?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;
?>

The expression uses the capturing group ([0-9]+) to match any integer and capture its value. Then, it uses /$1/ as a replacement. Notice $1 is a backreference to the value captured by the group.

For example:

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

captures "3" in group 1 and /$1/ is evaluated in the replacement as "/3/".

Upvotes: 1

jpaljasma
jpaljasma

Reputation: 1612

Capture the value between () and project it back via $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,}) means one or more digits. Hope this helps.

Upvotes: 1

Related Questions