string
ModuleByte-string functions of ext/standard/string.c and ext/ctype, plus
crypt(), password_hash() / password_verify() and hash().
PHP strings are byte strings: every function here takes and returns
&[u8] / Vec<u8>, never assumes UTF-8 and handles invalid UTF-8 like
any other byte. Case mapping (strtolower, ucfirst, stripos, ...) is
ASCII-only, as in PHP 8.2 and later.
Callers holding a &str pass s.as_bytes(). For valid UTF-8 arguments
these keep the result valid UTF-8, so String::from_utf8 (or
std::str::from_utf8) on it cannot fail: the case functions, trim
family with an ASCII character list (such as TRIM_CHARACTERS),
str_replace/strtr_array with UTF-8 strings, explode. Functions that
work on single bytes or byte positions (substr, strtr with non-ASCII
bytes) may split a character, as in PHP.
Arguments PHP takes as int (offsets, lengths) are i64, with PHP's
negative-offset rules. Results that PHP returns as false are None.
Errors PHP throws are Error, one variant per exception class, with
PHP's message.
| PHP | Rust |
|---|---|
strtolower, strtoupper, ucfirst, lcfirst, ucwords | strtolower, strtoupper, ucfirst, lcfirst, ucwords |
trim, ltrim, rtrim | trim, ltrim, rtrim (TRIM_CHARACTERS is the default) |
substr | substr |
stripos | stripos |
str_contains, str_starts_with | str_contains, str_starts_with |
strcmp, strcasecmp | strcmp, strcasecmp |
str_replace | str_replace, str_replace_array |
strtr | strtr, strtr_array |
explode | explode |
addcslashes, stripcslashes | addcslashes, stripcslashes |
strip_tags (no allowed tags) | strip_tags |
escapeshellarg | escapeshellarg |
ctype_alnum, ctype_digit, ctype_xdigit | ctype_alnum, ctype_digit, ctype_xdigit (Ctype for any value) |
(string) $value (zval_get_string) | to_php_string |
Every function here is checked against the real PHP function by
bin/compat fuzz php-std (operations string.*).
Contents
1 submodule, and what the module defines itself.
use php_std::string::Ctype;pub enum CtypeA ctype_* function, for calls with a value that may not be a string.
use php_std::string::Error;pub enum ErrorAn exception a PHP string, multibyte, encoding or formatting function throws: one variant per PHP exception class, carrying PHP's message.
Display.use php_std::string::Replace;pub enum Replace<'a>The $replace of an array-$search str_replace.
use php_std::string::addcslashes;pub fn addcslashes<'a>(s: &'a [u8], characters: &[u8]) -> Cow<'a, [u8]>PHP addcslashes($string, $characters): backslash-escapes the bytes of
characters (with a..z ranges); those outside printable ASCII become
\n, \t, \r, \a, \v, \b, \f or a 3-digit octal escape.
use php_std::string::charmask;pub fn charmask(chars: &[u8]) -> [bool; 256]php_charmask: the set of bytes a trim/ucwords/addcslashes
character list names. a..z adds an inclusive range; a malformed range
(PHP warns) adds what PHP adds: for "a.." that is a and the last ..
use php_std::string::crypt;pub fn crypt(string: &[u8], salt: &[u8]) -> Vec<u8>PHP crypt($string, $salt): the hash, or *0 (*1 when the salt starts
with *0) where the salt names no supported algorithm or is invalid.
The algorithms are PHP's own: blowfish ($2a$, $2b$, $2x$, $2y$),
MD5 ($1$), SHA-256 ($5$), SHA-512 ($6$), and FreeSec's DES
(two salt characters) and extended DES (_).
use php_std::string::ctype_alnum;pub fn ctype_alnum(s: &[u8]) -> boolPHP ctype_alnum on a string: non-empty and all ASCII letters or digits.
use php_std::string::ctype_digit;pub fn ctype_digit(s: &[u8]) -> boolPHP ctype_digit on a string: non-empty and all 0-9.
use php_std::string::ctype_xdigit;pub fn ctype_xdigit(s: &[u8]) -> boolPHP ctype_xdigit on a string: non-empty and all hexadecimal digits.
use php_std::string::escapeshellarg;pub fn escapeshellarg(arg: &[u8]) -> Result<Vec<u8>, Error>PHP escapeshellarg($arg) on Unix: the argument between single quotes,
each ' written as '\'', so a POSIX shell reads it back as one word.
Bytes are read as multibyte characters of the locale PHP runs in
(C.UTF-8, PHP's default since 8.0): a valid UTF-8 character is copied
whole, and a byte that does not start one is dropped (mblen() fails on
it). A NUL byte raises ValueError, as in PHP.
use php_std::string::escapeshellarg;
assert_eq!(escapeshellarg(b"it's").unwrap(), b"'it'\\''s'");
assert_eq!(escapeshellarg(b"caf\xc3\xa9\xff").unwrap(), "'caf\u{e9}'".as_bytes());
assert_eq!(escapeshellarg(b"a\0b").unwrap_err().php_class(), "ValueError");use php_std::string::explode;pub fn explode<'a>(separator: &[u8], s: &'a [u8], limit: i64) -> Result<Vec<&'a [u8]>, Error>PHP explode($separator, $string, $limit): the pieces between occurrences
of separator. A positive limit returns at most that many pieces (the
last holds the rest); a negative one drops that many pieces from the end;
0 is 1. An empty string gives [""] (or [] for a negative limit).
use php_std::string::hash;pub fn hash(algo: &[u8], data: &[u8]) -> Option<String>hash($algo, $data) as lowercase hex, for every algorithm of
hash_algos(); None for any other name (PHP's "must be a valid hashing
algorithm"). The name is case-insensitive.
use php_std::string::lcfirst;pub fn lcfirst(s: &[u8]) -> Cow<'_, [u8]>PHP lcfirst: lowercases the first byte if it is an ASCII letter.
use php_std::string::ltrim;pub fn ltrim<'a>(s: &'a [u8], characters: &[u8]) -> &'a [u8]PHP ltrim($string, $characters): like trim, start only.
use php_std::string::password_hash_argon2id;pub fn password_hash_argon2id(password: &[u8], memory_cost: i64, time_cost: i64, threads: i64, salt: &[u8; 16]) -> Result<Vec<u8>, Error>password_hash($password, PASSWORD_ARGON2ID, $options) with the
options' memory_cost, time_cost and threads (already cast to int)
and salt (16 random bytes in PHP).
use php_std::string::password_hash_bcrypt;pub fn password_hash_bcrypt(password: &[u8], cost: i64, salt: &[u8; 16]) -> Result<Vec<u8>, Error>password_hash($password, PASSWORD_BCRYPT, ['cost' => $cost]) with
salt (16 random bytes in PHP).
use php_std::string::password_verify;pub fn password_verify(password: &[u8], hash: &[u8]) -> boolPHP password_verify($password, $hash).
use php_std::string::php_crypt;pub fn php_crypt(password: &[u8], salt: &[u8]) -> Option<Vec<u8>>php_crypt(): crypt() without the failure strings. Both arguments are
C strings (they end at the first NUL).
use php_std::string::rtrim;pub fn rtrim<'a>(s: &'a [u8], characters: &[u8]) -> &'a [u8]PHP rtrim($string, $characters) (alias chop): like trim, end only.
use php_std::string::str_contains;pub fn str_contains(haystack: &[u8], needle: &[u8]) -> boolPHP str_contains.
use php_std::string::str_replace;pub fn str_replace<'a>(search: &[u8], replace: &[u8], subject: &'a [u8]) -> (Cow<'a, [u8]>, usize)PHP str_replace($search, $replace, $subject, $count) with string
arguments: replaces every occurrence of search (left to right, not
overlapping) and returns the result with $count. An empty search
changes nothing. Valid UTF-8 arguments give valid UTF-8.
use php_std::string::str_replace_array;pub fn str_replace_array<'a>(search: &[&[u8]], replace: Replace<'_>, subject: &'a [u8], case_insensitive: bool) -> (Cow<'a, [u8]>, usize)PHP str_replace / str_ireplace with an array $search: applies each
search/replacement pair in turn to the result of the previous one, skipping
empty search strings, and returns the total count. The array forms of
$subject apply this to each element (keys kept, counts summed); a string
$search with an array $replace is a TypeError in PHP and cannot be
expressed here.
use php_std::string::str_starts_with;pub fn str_starts_with(haystack: &[u8], needle: &[u8]) -> boolPHP str_starts_with.
use php_std::string::strcasecmp;pub fn strcasecmp(a: &[u8], b: &[u8]) -> i64PHP strcasecmp: strcmp on ASCII-lowercased bytes.
use php_std::string::strcmp;pub fn strcmp(a: &[u8], b: &[u8]) -> i64PHP strcmp: the byte difference at the first mismatch ("a" vs "c"
is -2), else -1, 0 or 1 by length.
use php_std::string::stripcslashes;pub fn stripcslashes(s: &[u8]) -> Vec<u8>PHP stripcslashes: decodes C-style escapes (\n, \t, \xhh, \ooo,
...); an unknown escape yields the escaped byte.
use php_std::string::stripos;pub fn stripos(haystack: &[u8], needle: &[u8], offset: i64) -> Result<Option<usize>, Error>PHP stripos($haystack, $needle, $offset): byte position of the first
ASCII case-insensitive occurrence at or after offset (negative: from
the end), None for false. An empty needle matches at the offset.
use php_std::string::strtolower;pub fn strtolower(s: &[u8]) -> Cow<'_, [u8]>PHP strtolower: ASCII A-Z to a-z; every other byte unchanged.
Borrows when nothing changes. Valid UTF-8 stays valid UTF-8.
use php_std::string::strtoupper;pub fn strtoupper(s: &[u8]) -> Cow<'_, [u8]>PHP strtoupper: ASCII a-z to A-Z; every other byte unchanged.
Borrows when nothing changes. Valid UTF-8 stays valid UTF-8.
use php_std::string::strtr;pub fn strtr<'a>(s: &'a [u8], from: &[u8], to: &[u8]) -> Cow<'a, [u8]>PHP strtr($string, $from, $to): translates each byte of from to the
byte at the same position of to, ignoring the extra bytes of the longer
one. When a byte appears twice in from, the last one wins.
use php_std::string::strtr_array;pub fn strtr_array<'a>(s: &'a [u8], pairs: &[(&[u8], &[u8])]) -> Cow<'a, [u8]>PHP strtr($string, $replace_pairs): at each position replaces the
longest key that matches, then continues after it; replaced text is never
rescanned. Empty keys are ignored (PHP warns). pairs is the array in
order, keys as PHP strings (integer keys as their decimal form); when a
key repeats, the last pair wins, as in a PHP array.
use php_std::string::substr;pub fn substr(s: &[u8], offset: i64, length: Option<i64>) -> &[u8]PHP substr($string, $offset, $length): a negative offset counts from
the end; a negative length stops that many bytes before the end;
None takes the rest. Out-of-range values clamp; never fails.
use php_std::string::to_php_string;pub fn to_php_string(value: &Value) -> Result<Cow<'_, str>, Error>PHP's string conversion of a value as string functions perform it
(zval_get_string): null and false are "", true is "1",
integers in decimal, floats with precision 14 (number::to_string),
arrays "Array" (PHP also warns). A stdClass (an empty JSON object)
has no string form: PHP's Error.
use php_std::string::trim;pub fn trim<'a>(s: &'a [u8], characters: &[u8]) -> &'a [u8]PHP trim($string, $characters): strips the bytes of characters (with
a..z ranges, see charmask) from both ends. Pass TRIM_CHARACTERS
for PHP's default.
use php_std::string::ucfirst;pub fn ucfirst(s: &[u8]) -> Cow<'_, [u8]>PHP ucfirst: uppercases the first byte if it is an ASCII letter.
use php_std::string::ucwords;pub fn ucwords<'a>(s: &'a [u8], separators: &[u8]) -> Cow<'a, [u8]>PHP ucwords($string, $separators): uppercases (ASCII) the first byte
and every byte that follows one of separators. separators accepts
a..z ranges like trim. Pass UCWORDS_SEPARATORS for PHP's default.
As in PHP, the separator test looks at the previous byte after it was
uppercased, so ucwords("aab", "A") is "AAB".
pub const NO_LIMIT: i64 = i64::MAXexplode's default $limit (PHP_INT_MAX): no limit.
pub const TRIM_CHARACTERS: &[u8] = b" \n\r\t\x0b\0"The default character list of trim, ltrim and rtrim: " \n\r\t\v\0".
pub const UCWORDS_SEPARATORS: &[u8] = b" \t\r\n\x0c\x0b"The default $separators of ucwords: " \t\r\n\f\v".
string::tables
Own pageConstant tables of PHP's ext/hash for hash() (from php-src 8.5:
php_hash_tiger_tables.h, php_hash_snefru_tables.h and hash_haval.c,
PHP License 3.01).