3v4l.org

run code in 300+ PHP versions simultaneously
<?php final class IntFilter { public static function check(int $value, array $options = array()) { return $value; } } final class StringFilter { public static function check(string $value, array $options = array()) { // Trim if (false !== ($options['trim'] ?? true)) { $value = trim($value); } $length = mb_strlen($value, '8bit'); // Empty if (false === ($options['empty'] ?? true)) { if (0 === $length) { throw new LengthException('chaine vide !'); } } // Min & max length if (isset($options['max'])) { $maxLength = IntFilter::check($options['max'], ['min' => 1]); if ($length > $maxLength) { throw new LengthException('trop long !'); } } if (isset($options['min'])) { $minLength = IntFilter::check($options['min'], ['min' => 1]); if ($length < $minLength) { throw new LengthException('trop court !'); } } if (isset($options['startsWith'])) { $needle = StringFilter::check($options['startsWith']); if (false === self::startsWith($value, $needle)) { throw new InvalidArgumentException('mauvais début !'); } } if (isset($options['endsWith'])) { $needle = StringFilter::check($options['endsWith']); if (false === self::endsWith($value, $needle)) { throw new InvalidArgumentException('mauvaise fin !'); } } return $value; } private static function startsWith($haystack, $needle) { return $haystack[0] === $needle[0] ? strncmp($haystack, $needle, mb_strlen($needle, '8bit')) === 0 : false; } private static function endsWith($haystack, $needle) { $length = mb_strlen($needle, '8bit'); $haystack = mb_substr($haystack, -$length); return $haystack[0] === $needle[0] ? strncmp($haystack, $needle, $length) === 0 : false; } } var_dump(StringFilter::check(' test ', ['endsWith' => 'st']));

preferences:
31.43 ms | 402 KiB | 5 Q