preg_replace() replace second occurrence

后端 未结 3 1373
没有蜡笔的小新
没有蜡笔的小新 2020-12-19 19:57

This is what I do now:

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

I re

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-19 20:12

    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 );
      }
    }
    

    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.

    See this working here.

提交回复
热议问题