[php-src] PR #21429: Add FILTER_VALIDATE_STRLEN for UTF-8 string length validation
| From: | masakielastic | Date: | Fri, 13 Mar 2026 02:22:33 +0000 |
| Subject: | [php-src] PR #21429: Add FILTER_VALIDATE_STRLEN for UTF-8 string length validation | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-35188@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/21429
Author: masakielastic
This PR introduces a new filter validator FILTER_VALIDATE_STRLEN.
The validator checks the length of a UTF-8 string in Unicode code points and allows applications to
enforce minimum and/or maximum string length.
**API**
New filter constant:
```
FILTER_VALIDATE_STRLEN
```
Supported options:
```
min_len int minimum accepted length (in Unicode code points)
max_len int maximum accepted length (in Unicode code points)
```
Example:
```
$options = [
'options' => [
'min_len' => 2,
'max_len' => 2,
],
];
var_dump(
filter_var('ab', FILTER_VALIDATE_STRLEN, $options),
filter_var('🐘🐘', FILTER_VALIDATE_STRLEN, $options),
filter_var('🐘', FILTER_VALIDATE_STRLEN, $options),
filter_var('🐘🐘🐘', FILTER_VALIDATE_STRLEN, $options)
);
```
**Implementation notes**
The implementation:
* counts UTF-8 code points
* reuses UTF-8 handling logic already present in core (similar to the implementation used by
htmlspecialchars)
**Motivation**
Validating the length of UTF-8 strings is a common requirement in applications (e.g. form input
validation).
Currently this is typically implemented in userland using:
* mb_strlen() from the mbstring extension
* framework or CMS polyfills
* custom helpers
Providing a dedicated validator in the filter extension allows this validation to be performed in a
lightweight and consistent way without introducing a dependency on mbstring.
**Related discussion**
See issue #21428