Reputation: 13
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?
Upvotes: 0
Views: 73
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
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