preg_replace() 替换第二次出现 [英] preg_replace() replace second occurrence

查看:83
本文介绍了preg_replace() 替换第二次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我现在所做的:

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

我用 for ex 替换了 nl.de .但现在我想替换第二次出现.最简单的方法是什么?

I replace the nl with for ex. de . But now I want to replace the second occurrence. What's the easiest way to do this?

推荐答案

所以首先你检查是否有任何发生,如果有,你就替换它.您可以计算出现次数(取消substr_count) 而不是知道它们中有多少存在.然后,如果需要,只需一点一点地替换它们.

So firstly you check if there is any occurrence and if so, you replace it. You could count the occurrences (unsing substr_count) instead to know how many of them exist. Then, just replace them bit by bit if that's what you need.

$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 中的字符串函数.您可以使用使用 strpos 找到的第一次出现作为 substr 的开始,然后将其用于替换.

If you only want to replace the second occurrence (as stated by you later on in the comments), check out substr and read up on string functions in PHP. You can use the first occurrence, found using strpos as a start for substr and just use that for your replacement.

<?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;

此处查看此工作.

这篇关于preg_replace() 替换第二次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆