微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐