preg_replace()替换第二次出现

时间:2014-04-23 08:40:12

标签: php replace preg-replace

这就是我现在所做的:

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

我用ex替换nlde。但现在我想替换second occurrence。最简单的方法是什么?

3 个答案:

答案 0 :(得分:8)

@Casimir的答案似乎适用于大多数情况。另一种选择是preg_replace_callback带有计数器。如果您需要仅更换特定的第n次出现。

smoothed

这利用了本地variance,在每次出现的回调中递增,并且只是在这里检查了固定位置。

答案 1 :(得分:3)

首先,您检查是否有任何问题,如果是,请更换它。 您可以计算出现次数( unsing substr_count ),而不知道它们中有多少存在。 然后,如果这就是你需要的,那就一点一点地替换它们。

$occurances = substr_count($routeName, '/nl/');
if ($occurances > 0) {
  $routeName = preg_replace('/nl/', $lang , $routeName, 1 );
  if ($occurances > 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;

请参见此工作here

答案 2 :(得分:1)

你可以这样做:

$lang = 'de'
$routeName = preg_replace('~/nl/.*?(?<=/)\Knl/~', "$lang/", $routeName, 1 );

\K将从匹配结果中删除左侧的所有内容。(因此,左侧与/nl/.*?(?<=/)匹配的所有内容都不会被替换。) < / p>

我使用lookbehind (?<=/)而不是文字/来处理此特定情况/nl/nl/ (在这种情况下,.*?匹配空子字符串。)

相关问题