PHP 8 reference · 61 entries

PHP String Functions

PHP string functions from strlen() and str_replace() to sprintf() and htmlspecialchars(), with syntax, PHP 8 changes and examples you can run.

These functions work on bytes. That's fine for ASCII text, but in UTF-8 a letter like é takes two bytes, so lengths and positions can be off. For user-facing text use the multibyte functions such as mb_strlen() and mb_substr(). Strings are values in PHP: every function returns a new string and leaves the original unchanged.

NameDescriptionSince
strlen() Return the length of a string in bytes. Multibyte characters such as é count as several bytes; use mb_strlen() to count characters. 4.0
str_word_count() Count the words in a string, or return them as an array. Words are runs of letters plus ' and -; digits split words. 4.3
strtolower() Convert every ASCII letter in a string to lowercase. Since PHP 8.2 it ignores the locale; use mb_strtolower() for é, Ü and others. 4.0
strtoupper() Convert every ASCII letter in a string to uppercase. Letters such as é stay unchanged; use mb_strtoupper() for those. 4.0
ucfirst() Make the first character of a string uppercase and leave the rest as it is. Only ASCII letters change. 4.0
lcfirst() Make the first character of a string lowercase, leaving the rest unchanged. Handy for turning PascalCase into camelCase. 5.3
ucwords() Uppercase the first letter of each word in a string. By default words are separated by spaces, tabs and new lines. 4.0
trim() Remove whitespace (or other characters you choose) from both ends of a string. Spaces inside the string are kept. 4.0
ltrim() Remove whitespace or other chosen characters from the start (left side) of a string only. 4.0
rtrim() Remove whitespace or other chosen characters from the end (right side) of a string. chop() is an alias. 4.0
str_pad() Pad a string to a given length with spaces or another string, on the right, left or both sides. 4.0
str_repeat() Repeat a string a given number of times and return the result. A count of 0 returns an empty string. 4.0
strrev() Reverse a string byte by byte. Fine for ASCII, but it breaks multibyte characters such as é. 4.0
str_replace() Replace every occurrence of a search string with a replacement. Accepts arrays to make several replacements at once. 4.0
str_ireplace() Replace every occurrence of a search string, ignoring upper and lower case. Otherwise works like str_replace(). 5.0
substr_replace() Replace part of a string, given a start position and length, with another string. Also inserts text or masks digits. 4.0
strtr() Translate characters, or replace substrings in one pass using an array of from => to pairs. Longest keys match first. 4.0
substr() Return part of a string, given a start position and an optional length. Negative values count from the end. 4.0
strpos() Find the position of the first occurrence of a substring. Returns false if it's not found, so compare with === false. 4.0
stripos() Find the position of the first occurrence of a substring, ignoring case. Returns false when there's no match. 5.0
strrpos() Find the position of the last occurrence of a substring in a string. Returns false if it isn't found. 4.0
strstr() Return the part of a string from the first occurrence of a substring to the end, or the part before it. 4.0
strrchr() Return the part of a string from the last occurrence of a character to the end. Only the first character of the needle is used. 4.0
str_contains() Check whether a string contains a substring and return true or false. Case-sensitive; added in PHP 8.0. 8.0
str_starts_with() Check whether a string begins with a given substring. Case-sensitive and returns true or false; added in PHP 8.0. 8.0
str_ends_with() Check whether a string ends with a given substring, such as a file extension. Case-sensitive; added in PHP 8.0. 8.0
substr_count() Count how many times a substring occurs in a string. Matches don't overlap, and the search is case-sensitive. 4.0
explode() Split a string into an array by a separator, like turning "a,b,c" into ["a", "b", "c"]. A limit caps the pieces. 4.0
implode() Join array elements into one string with a separator between them. join() is an alias of implode(). 4.0
str_split() Split a string into an array of chunks of a given length, one byte each by default. Use mb_str_split() for UTF-8. 5.0
str_getcsv() Parse one line of CSV text into an array of fields, handling quoted values that contain commas or quotes. 5.3
wordwrap() Wrap a string at a given line width by inserting line breaks between words, optionally cutting long words. 4.0
nl2br() Insert an HTML <br> tag before every new line in a string, so plain text keeps its line breaks on a web page. 4.0
htmlspecialchars() Convert &, <, >, " and ' to HTML entities so user text is shown as text, not run as HTML. The main defence against XSS. 4.0
html_entity_decode() Convert HTML entities such as &amp;, &lt; and &eacute; back into the characters they stand for. 4.3
strip_tags() Remove HTML and PHP tags from a string, keeping the text. You can allow some tags, but it's no XSS protection. 4.0
addslashes() Add a backslash before quotes, backslashes and NUL bytes. Not a safe way to build SQL: use prepared statements. 4.0
sprintf() Return a formatted string built from a template with placeholders like %s, %d and %.2f. Format numbers, pad and align. 4.0
printf() Output a formatted string, using the same placeholders as sprintf(), and return the number of bytes printed. 4.0
vsprintf() Format a string like sprintf(), but take the values from an array. Useful when the number of values varies. 4.1
number_format() Format a number with grouped thousands and a fixed number of decimals, such as 1,234,567.89 or 1.234,57. 4.0
strcmp() Compare two strings byte by byte, case-sensitively. Returns 0 when equal, less than 0 or more than 0 otherwise. 4.0
strcasecmp() Compare two strings without caring about ASCII upper and lower case. Returns 0 if they match. 4.0
strncmp() Compare only the first n bytes of two strings, case-sensitively. Handy for checking a prefix in older code. 4.0
strnatcmp() Compare strings in natural order, so "img2" comes before "img10" the way people expect. Case-sensitive. 4.0
strnatcasecmp() Compare strings in natural order ("a2" before "a10") while ignoring upper and lower case. 4.0
similar_text() Calculate how similar two strings are, as a count of matching characters and optionally as a percentage. 4.0
levenshtein() Calculate the edit distance between two strings: the fewest insertions, deletions and replacements to turn one into the other. 4.0
soundex() Return a four-character code for how an English word sounds, so names like Robert and Rupert can be matched. 4.0
md5() Calculate the MD5 hash of a string as 32 hex characters. Fine for checksums and cache keys, never for passwords. 4.0
sha1() Calculate the SHA-1 hash of a string as 40 hex characters. Weak for security; prefer hash("sha256", ...). 4.3
hash() Hash a string with the algorithm you choose, such as sha256, sha512, crc32b or xxh3. Returns a hex string. 5.1
base64_encode() Encode binary data or text as Base64, using only letters, digits, + and /, so it travels safely as text. 4.0
base64_decode() Decode a Base64 string back to the original data. With strict mode on, invalid input returns false. 4.0
urlencode() Encode a string for a URL query value: spaces become + and special characters become %XX codes. 4.0
rawurlencode() Encode a string per RFC 3986: spaces become %20. Use it for URL path segments. 4.0
http_build_query() Build a URL-encoded query string, such as page=2&sort=name, from an array. Nested arrays become key[]=... pairs. 5.0
parse_str() Parse a query string such as a=1&b=2 into an array, the reverse of http_build_query(). The result argument is required. 4.0
ord() Return the value (0 to 255) of the first byte of a string, such as 65 for "A". The reverse of chr(). 4.0
chr() Return the one-byte character for a value from 0 to 255, such as "A" for 65. The reverse of ord(). 4.0
bin2hex() Convert binary data to a hexadecimal string, two hex digits per byte. Often used to print random bytes as a token. 4.0

Was this page helpful?