[wp-trac] [WordPress Trac] #63804: Proposal of wp_trim(): JavaScript-compatible alternative for trim()
WordPress Trac
noreply at wordpress.org
Sat Aug 9 09:07:51 UTC 2025
#63804: Proposal of wp_trim(): JavaScript-compatible alternative for trim()
--------------------------+-----------------------------
Reporter: takayukister | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Formatting | Version:
Severity: normal | Keywords:
Focuses: |
--------------------------+-----------------------------
PHP's [https://www.php.net/manual/en/function.trim.php trim()] function,
by default, only strips limited ASCII characters of whitespace. On the
other hand, JavaScript's [https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/String/trim
String.prototype.trim()] method strips all Unicode white space characters
and line terminators. This difference often confuses.
PHP 8.4 introduced [https://www.php.net/manual/en/function.mb-trim.php
mb_trim()], the multi-byte safe alternative for `trim()`. Unfortunately,
though, `String.prototype.trim()` and `mb_trim()` do not perform
identically. There are slight differences: `String.prototype.trim()`
strips `U+FEFF` (Zero-width no-break space); `mb_trim()` doesn't.
For safe coding, I propose introducing `wp_trim()`, a PHP function that
performs identically to `String.prototype.trim()`. The following is a
simple implementation example of `wp_trim()`:
{{{#!php
function wp_trim( string $string ): string {
$whitespaces =
'\x09-\x0D\x20\x85\xA0\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}\x{FEFF}';
$string = preg_replace(
sprintf( '/[%s]+$/u', $whitespaces ),
'',
$string
);
$string = preg_replace(
sprintf( '/^[%s]+/u', $whitespaces ),
'',
$string
);
return $string;
}
}}}
Among the white space characters that `wp_trim()` strips, `U+3000`
(Ideographic space) is one especially often used in Japanese user-
generated content. It is also called "full-width space", which is the
character input when you hit the space bar in the Japanese input mode. I
think we should replace `trim()` with `wp_trim()` anywhere you use it for
trimming user input text.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/63804>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list