Bolt\Helpers\Str::replaceLast PHP Method

replaceLast() public static method

Replace only the last occurrence of the $search text on the $subject.
public static replaceLast ( string $search, string $replace, string $subject, boolean $caseSensitive = true ) : string
$search string
$replace string
$subject string
$caseSensitive boolean
return string
    public static function replaceLast($search, $replace, $subject, $caseSensitive = true)
    {
        $pos = $caseSensitive ? strrpos($subject, $search) : strripos($subject, $search);
        if ($pos !== false) {
            $subject = substr_replace($subject, $replace, $pos, strlen($search));
        }
        return $subject;
    }

Usage Example

Example #1
0
 /**
  * Gather related (present) files.
  *
  * Matches: foo(_local)?\.*(.dist)?
  *
  * i.e., if we're editing config.yml, we also want to check for
  * config.yml.dist and config_local.yml
  *
  * @param FileInterface $file
  *
  * @return FileInterface[]
  */
 private function getRelatedFiles(FileInterface $file)
 {
     // Match foo(_local).*(.dist)
     $base = $file->getFilename();
     if (Str::endsWith($base, '.dist')) {
         $base = substr($base, 0, -5);
     }
     $ext = pathinfo($base, PATHINFO_EXTENSION);
     $base = Str::replaceLast(".{$ext}", '', $base);
     $base = Str::replaceLast('_local', '', $base);
     $dir = $file->getParent();
     $related = [];
     foreach ([".{$ext}", "_local.{$ext}", ".{$ext}.dist"] as $tail) {
         $f = $dir->getFile($base . $tail);
         if ($f->getFilename() !== $file->getFilename() && $f->exists()) {
             $related[] = $f;
         }
     }
     return $related;
 }