diff --git a/src/Latte/Essential/Filters.php b/src/Latte/Essential/Filters.php index af7a9ee7e..107b44f44 100644 --- a/src/Latte/Essential/Filters.php +++ b/src/Latte/Essential/Filters.php @@ -487,6 +487,44 @@ public static function trim(FilterInfo $info, string $s, string $charlist = " \t return $s; } + + + /** + * Strip whitespace (or other characters) from the beginning of a string. + */ + public static function ltrim(FilterInfo $info, string $s, string $charlist = " \t\n\r\0\x0B\u{A0}"): string + { + if ($charlist === "") { + return $s; + } + + $charlist = preg_quote($charlist, '#'); + $s = preg_replace('#^[' . $charlist . ']+#Du', '', $s); + if (preg_last_error() || $s === null) { + throw new Latte\RuntimeException(preg_last_error_msg()); + } + + return $s; + } + + + /** + * Strip whitespace (or other characters) from the end of a string. + */ + public static function rtrim(FilterInfo $info, string $s, string $charlist = " \t\n\r\0\x0B\u{A0}"): string + { + if ($charlist === "") { + return $s; + } + + $charlist = preg_quote($charlist, '#'); + $s = preg_replace('#[' . $charlist . ']+$#Du', '', $s); + if (preg_last_error() || $s === null) { + throw new Latte\RuntimeException(preg_last_error_msg()); + } + + return $s; + } /** diff --git a/tests/filters/ltrim.phpt b/tests/filters/ltrim.phpt new file mode 100644 index 000000000..13cb1ba38 --- /dev/null +++ b/tests/filters/ltrim.phpt @@ -0,0 +1,25 @@ + Filters::ltrim($info, "\xC2x\xA0"), + Latte\RuntimeException::class, + null, +); diff --git a/tests/filters/rtrim.phpt b/tests/filters/rtrim.phpt new file mode 100644 index 000000000..18c689105 --- /dev/null +++ b/tests/filters/rtrim.phpt @@ -0,0 +1,25 @@ + Filters::rtrim($info, "\xC2x\xA0"), + Latte\RuntimeException::class, + null, +);