Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/Latte/Essential/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}


/**
Expand Down
25 changes: 25 additions & 0 deletions tests/filters/ltrim.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php declare(strict_types=1);

/**
* Test: Latte\Essential\Filters::ltrim()
*/

use Latte\ContentType;
use Latte\Essential\Filters;
use Latte\Runtime\FilterInfo;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


$info = new FilterInfo(ContentType::Text);
Assert::same('x', Filters::ltrim($info, " \t\n\r\x00\x0B\u{A0}x"));
Assert::same('a b ', Filters::ltrim($info, ' a b '));
Assert::same(' a b ', Filters::ltrim($info, ' a b ', ''));
Assert::same('e-', Filters::ltrim($info, "\u{158}e-", "\u{158}-")); // Ře-

Assert::exception(
fn() => Filters::ltrim($info, "\xC2x\xA0"),
Latte\RuntimeException::class,
null,
);
25 changes: 25 additions & 0 deletions tests/filters/rtrim.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php declare(strict_types=1);

/**
* Test: Latte\Essential\Filters::rtrim()
*/

use Latte\ContentType;
use Latte\Essential\Filters;
use Latte\Runtime\FilterInfo;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


$info = new FilterInfo(ContentType::Text);
Assert::same('x', Filters::rtrim($info, "x \t\n\r\x00\x0B\u{A0}"));
Assert::same(' a b', Filters::rtrim($info, ' a b '));
Assert::same(' a b ', Filters::rtrim($info, ' a b ', ''));
Assert::same('e', Filters::rtrim($info, "e\u{158}-", "\u{158}-")); // eŘ-

Assert::exception(
fn() => Filters::rtrim($info, "\xC2x\xA0"),
Latte\RuntimeException::class,
null,
);