diff --git a/README.md b/README.md index 55f6a5b..d0e078c 100644 --- a/README.md +++ b/README.md @@ -349,12 +349,12 @@ print_r($statement->params()); // ["\%\%hijack"]; ``` -The `LikeValue` helper also supports adding wildcards before and after the -value automatically: +The `LikeValue` helper also supports adding wildcards value automatically: ```php -echo like::any('John'); -// "%John%" +echo like::any('John'); // "%John%" +echo like::starts('Joh'); // "Joh%" +echo like::ends('ohn'); // "%ohn" ``` There is also a MSSQL extension that will escape character ranges: diff --git a/src/LikeValue.php b/src/LikeValue.php index 5aadc80..2cfdfdf 100644 --- a/src/LikeValue.php +++ b/src/LikeValue.php @@ -27,4 +27,22 @@ public static function any(string $value): string $value = static::escape($value); return "%$value%"; } + + /** + * Escape input for a LIKE condition, ends with wildcards. + */ + public static function starts(string $value): string + { + $value = static::escape($value); + return "$value%"; + } + + /** + * Escape input for a LIKE condition, starts with wildcards. + */ + public static function ends(string $value): string + { + $value = static::escape($value); + return "%$value"; + } } diff --git a/tests/LikeValueTest.php b/tests/LikeValueTest.php index f84efe0..b52c07e 100644 --- a/tests/LikeValueTest.php +++ b/tests/LikeValueTest.php @@ -22,4 +22,20 @@ public function testLikeAny() $this->assertSame($expected, LikeValue::any($input)); } + + public function testLikeStarts() + { + $input = 'a % string'; + $expected = 'a \\% string%'; + + $this->assertSame($expected, LikeValue::starts($input)); + } + + public function testLikeEnds() + { + $input = 'a % string'; + $expected = '%a \\% string'; + + $this->assertSame($expected, LikeValue::ends($input)); + } }