php-preg_replace()替换第二次出现

这就是我现在要做的:

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

我将ex替换为nl. de.但是现在我要替换第二次出现的情况.最简单的方法是什么?

解决方法:

因此,首先您检查是否发生任何事件,如果发生,则将其替换.
您可以计算发生次数(取消计数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.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...