Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace() replace second occurrence

This is what I do now:

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

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?

like image 526
nielsv Avatar asked Nov 30 '22 01:11

nielsv


2 Answers

The answer by @Casimir seems rather applicable to most cases. Another alternative is preg_replace_callback with a counter. In case you need a specific n-th occurence to be replaced only.

#-- regex-replace an occurence by count
$s = "…abc…abc…abc…";
$counter = 1;
$s = preg_replace_callback("/abc/", function ($m) use (&$counter) {

     #-- replacement for 2nd occurence of "abc"
     if ($counter++ == 2) {
          return "def";
     }

     #-- else leave current match
     return $m[0];

}, $s);

This utilizes a local $counter, incremented within the callback on each occurence, and there simply checked for a fixed position here.

like image 137
mario Avatar answered Dec 04 '22 01:12

mario


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.

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

See this working here.

like image 25
Andresch Serj Avatar answered Dec 04 '22 01:12

Andresch Serj