3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php final class Filename { /** * @var string */ private $basename; /** * @var string */ private $extension; /** * Filename constructor. * * @param string $filename * @param array $replace */ public function __construct(string $filename, array $replace = []) { $info = pathinfo($filename); $info = array_map('strtolower', $info); if (array_key_exists('extension', $info)) { $this->setExtension($info['extension']); } if (empty($replace)) { $replace = [ ' ' => '_', 'Ä' => 'Ae', 'Ö' => 'Oe', 'Ü' => 'Ue', 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss' ]; } print_r($info); $this->basename = self::clean($info['filename'], $replace); } /** * @param int $length * * @throws \Exception */ public function limitLength(int $length) { assure($length > 0, 'Invalide Länge: %d', $length); if (strlen($this->basename) > $length) { $this->basename = substr($this->basename, 0, $length); } } /** * @param string $str * @param array $replace * * @return string */ public static function clean(string $str, array $replace = []): string { $str = trim($str); $str = trim($str, '_-'); if (!empty($replace)) { $str = str_replace(array_keys($replace), array_values($replace), $str); } $str = preg_replace('#[^\w\-]+#i', '_', $str); //Mehrere aufeinanderfolgende Unterstriche zu einem Unterstrich $str = preg_replace('#_+#', '_', $str); //Bindestrich vor Unterstrich zum Bindestrich $str = preg_replace('#\-_#', '-', $str); //Bindestrich nach Unterstrich zum Bindestrich $str = preg_replace('#_\-#', '-', $str); //Unterstrich am Ende zu nix $str = preg_replace('#_$#', '', $str); return $str; } /** * @return null|string */ public function getExtension() { return $this->extension; } /** * @return bool */ public function hasExtension(): bool { return $this->extension !== null; } /** * @param string $extension */ public function setExtension(string $extension) { if (MimeTypes::isExtensionSupported($extension)) { $this->extension = $extension; } } /** * @return string */ public function getBasename(): string { return $this->basename; } /** * @return bool */ public function isValid(): bool { return strlen($this->getBasename()) !== 0 && $this->hasExtension(); } /** * @return string */ public function assemble(): string { if ($this->hasExtension()) { return sprintf('%s.%s', $this->getBasename(), $this->getExtension()); } return $this->getBasename(); } } $file = 'Versicherungsschein/Nachträge'; var_dump(new Filename($file));