preg_replace()替换第二个出现

4

这是我现在所做的:

if (strpos($routeName,'/nl/') !== false) {
    $routeName = preg_replace('/nl/', $lang , $routeName, 1 );
}

我将nl替换为例如de。但现在我想要替换第二次出现。最简单的方法是什么?


如果使用正确,preg_replace可以替换所有出现的/nl/$lang。如果您想要替换第二个出现的内容,为什么不只是重复您的代码呢?也许可以阅读一下手册:http://www.php.net/manual/en/function.preg-replace.php - Andresch Serj
使用 preg_match 函数可以返回一个匹配的数组,然后可以使用 str_replace 函数来替换数组中的第二个元素。 - Aysennoussi
1
可能是重复的问题:PHP:preg_replace(x)出现? - clami219
您也可以查看这里 - Thamilhan
3个回答

15

@Casimir提供的答案似乎适用于大多数情况。另一种选择是使用preg_replace_callback和计数器。如果您只需要替换特定的第n个出现。

#-- regex-replace an occurence by count
$s = "…abc…abc…abc…";
$counter = 1;
$s = preg_replace_callback("/abc/", function ($m) use (&$counter) {

     #-- replacement for 2nd occurence of "abc"
     if ($counter++ == 2) {
          return "def";
     }

     #-- else leave current match
     return $m[0];

}, $s);

这里利用了一个本地的$counter,在回调函数中每次出现时递增,并在此处仅检查固定位置。


4
首先检查是否有任何出现,如果有,就将其替换。 您可以计算出现次数(使用substr_count)),以了解它们的数量。 然后,如果需要,逐个替换它们。
$occurrences = substr_count($routeName, '/nl/');
if ($occurrences > 0) {
  $routeName = preg_replace('/nl/', $lang , $routeName, 1 );
  if ($occurrences > 1) {  
    // second replace
    $routeName = preg_replace('/nl/', $lang , $routeName, 1 );
  }
}

如果你只想替换第二次出现的位置(如你在评论中所述),请查看 substr 并阅读 PHP 中的 string functions。你可以使用 strpos 找到第一次出现的位置,以此为起点使用 substr 进行替换。
<?php

$routeName = 'http://example.nl/language/nl/peter-list/foo/bar?example=y23&source=nl';
$lang = 'de';

$routeNamePart1 = substr( $routeName, 0 , strpos($routeName,'nl') +4 );
$routeNamePart2 = substr( $routeName, strpos($routeName,'nl') + 4);
$routeNamePart2 = preg_replace('/nl/', $lang , $routeNamePart2, 1 );
$routeName = $routeNamePart1 . $routeNamePart2;

echo $routeName;

在这里查看工作中的链接


2
你可以这样做:
$lang = 'de'
$routeName = preg_replace('~/nl/.*?(?<=/)\Knl/~', "$lang/", $routeName, 1 );
\K会将匹配结果左边的所有内容删除。(因此,与/nl/.*?(?<=/)匹配的左侧所有内容都不会被替换。) 在处理特定情况/nl/nl/时,我使用了回顾后发断言(?<=/)而不是字面上的/(在这种情况下,.*?匹配一个空子字符串。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接