Ouzo\Utilities\Strings::replaceNth PHP Метод

replaceNth() публичный статический Метод

public static replaceNth ( string $subject, string $search, string $replace, integer $nth ) : string
$subject string
$search string
$replace string
$nth integer
Результат string
    public static function replaceNth($subject, $search, $replace, $nth)
    {
        $found = preg_match_all('/' . $search . '/', $subject, $matches, PREG_OFFSET_CAPTURE);
        if (false !== $found && $found > $nth) {
            return substr_replace($subject, $replace, $matches[0][$nth][1], mb_strlen($search));
        }
        return $subject;
    }

Usage Example

Пример #1
0
 /**
  * @test
  */
 public function shouldReturnInputStringReplaceNthStringWhenNoSearchFound()
 {
     //given
     $subject = 'name = ? AND description =    ?';
     //when
     $replaceNth = Strings::replaceNth($subject, 'not there', 'IS NULL', 1);
     //then
     $this->assertEquals($subject, $replaceNth);
 }