开发者

preg_replace only part of match

开发者 https://www.devze.com 2022-12-28 03:34 出处:网络
I\'m using preg_replace to create urls for modrewrite based paging links. I use: $nextURL = preg_replace(\'%/([\\d]+)/%\',\'/\'.($pageNumber+1).\'/\',$currentURL);

I'm using preg_replace to create urls for modrewrite based paging links. I use:

$nextURL = preg_replace('%/([\d]+)/%','/'.($pageNumber+1).'/',$currentURL);

which works fine, however I was wondering if there is a better way without having to include the '/' in the replacement parameter. I need to match the number as being between two / as the URLs can sometimes contain numbers other than the page part. These numbers are never only numbers however, so have /[\d]+/ stops them开发者_如何学C from getting replaced.


You could use look-around assertions:

 %(?<=/)([\d]+)(?=/)%

(?<=…) is a positive look-behind assertion and (?=…) a positive look-ahead assertion. The regular expression (?<=/)([\d]+)(?=/) is to be interpreted as follows:

  • (?<=/) – if there is a / in behind the current position
  • ([\d]+) – match one or more digits
  • (?=/) – but only if there is a / after that

You can also simplify your expression as follows:

preg_replace('%(?<=/)\d+(?=/)%', $pageNumber+1, $currentURL)


Try

$nextURL = preg_replace('%(?<=/)([\d]+)(?=/)%',($pageNumber+1),$currentURL);
0

精彩评论

暂无评论...
验证码 换一张
取 消