php_ref_string
PHP String Functions
Section titled “PHP String Functions”PHP String Functions Introduction
Section titled “PHP String Functions Introduction”Strings are one of the fundamental data types in PHP, used to represent sequences of characters. PHP provides a rich set of built-in functions for manipulating strings.
These functions cover a wide range of operations, including:
- Searching and replacing text within strings.
- Formatting strings (e.g., padding, changing case, number formatting).
- Converting strings to/from arrays or other types.
- Comparing strings.
- Calculating string length or hash values.
- Encoding/decoding and escaping strings (e.g., for HTML or SQL).
These functions are part of the PHP core, so no installation is required to use them.
Important Note on Character Encoding: Many string functions operate correctly with multi-byte character sets (like UTF-8, which is standard for web content) if the appropriate mbstring (multi-byte string) extension is enabled and configured. For reliable handling of non-ASCII characters, prefer using the corresponding mb_* functions (e.g., mb_strlen() instead of strlen(), mb_strtolower() instead of strtolower()).
Security Considerations: When dealing with strings originating from user input, always sanitize and escape them appropriately before using them in different contexts (e.g., htmlspecialchars() for HTML output, prepared statements for SQL queries) to prevent security vulnerabilities like Cross-Site Scripting (XSS) and SQL Injection.
Commonly Used PHP String Functions
Section titled “Commonly Used PHP String Functions”Below is a comprehensive list of string functions available in PHP. While all are listed for reference, some key and frequently used functions include strlen, strpos, substr, str_replace, explode, implode, htmlspecialchars, trim, strtolower, strtoupper.
Function Description--------------------------- ------------------------------------------------------------------------addcslashes() Quote string with slashes in C styleaddslashes() Quote string with slashes for database usage (use prepared statements instead!)bin2hex() Convert binary data into hexadecimal representationchop() Alias of rtrim()chr() Generate a single-byte string from an ASCII valuechunk_split() Split a string into smaller chunksconvert_cyr_string() Convert from one Cyrillic character set to anotherconvert_uudecode() Decode a uuencoded stringconvert_uuencode() Uuencode a stringcount_chars() Return information about characters used in a stringcrc32() Calculate the crc32 polynomial of a stringcrypt() One-way string hashing (DEPRECATED for passwords - use password_hash())echo() Output one or more stringsexplode() Split a string by a string into an arrayfprintf() Write a formatted string to a streamget_html_translation_table() Returns the translation table used by htmlspecialchars() and htmlentities()hebrev() Convert logical Hebrew text to visual texthebrevc() Convert logical Hebrew text to visual text with newline conversionhex2bin() Decodes a hexadecimally encoded binary stringhtml_entity_decode() Convert HTML entities back to charactershtmlentities() Convert all applicable characters to HTML entitieshtmlspecialchars_decode() Convert special HTML entities back to charactershtmlspecialchars() Convert special characters to HTML entities (essential for security)implode() / join() Join array elements with a stringlcfirst() Make a string's first character lowercaselevenshtein() Calculate Levenshtein distance between two stringslocaleconv() Get numeric formatting informationltrim() Strip whitespace (or other characters) from the beginning of a stringmd5() Calculate the MD5 hash of a string (not secure for passwords)md5_file() Calculates the MD5 hash of a given file (not secure for passwords)metaphone() Calculate the metaphone key of a stringmoney_format() Formats a number as a currency string (Deprecated; use NumberFormatter)nl_langinfo() Query language and locale informationnl2br() Inserts HTML line breaks before all newlines in a stringnumber_format() Format a number with grouped thousandsord() Return ASCII value of the first character of a stringparse_str() Parses the string into variables (e.g., query string)print() Output a stringprintf() Output a formatted stringquoted_printable_decode() Convert a quoted-printable string to an 8-bit stringquoted_printable_encode() Convert an 8-bit string to a quoted-printable stringquotemeta() Quote meta charactersrtrim() Strip whitespace (or other characters) from the end of a stringsetlocale() Set locale informationsha1() Calculate the SHA-1 hash of a string (not secure for passwords)sha1_file() Calculate the SHA-1 hash of a file (not secure for passwords)similar_text() Calculate the similarity between two stringssoundex() Calculate the soundex key of a stringsprintf() Return a formatted stringsscanf() Parses input from a string according to a formatstr_contains() (PHP 8+) Determine if a string contains a given substringstr_ends_with() (PHP 8+) Checks if a string ends with a given substringstr_getcsv() Parse a CSV string into an arraystr_ireplace() Case-insensitive version of str_replace()str_pad() Pad a string to a certain length with another stringstr_repeat() Repeat a stringstr_replace() Replace all occurrences of the search string with the replacement stringstr_rot13() Perform the ROT13 transform on a stringstr_shuffle() Randomly shuffles a stringstr_split() Convert a string to an array of charactersstr_starts_with() (PHP 8+) Checks if a string starts with a given substringstr_word_count() Return information about words used in a stringstrcasecmp() Binary safe case-insensitive string comparisonstrchr() Alias of strstr()strcmp() Binary safe string comparison (case-sensitive)strcoll() Locale based string comparisonstrcspn() Find length of initial segment not matching maskstrip_tags() Strip HTML and PHP tags from a stringstripcslashes() Un-quote string quoted with addcslashes()stripslashes() Un-quote string quoted with addslashes() (less needed with proper escaping)stripos() Find position of first occurrence of a case-insensitive substringstristr() Case-insensitive strstr()strlen() Get string length (byte-based; use mb_strlen() for multi-byte)strnatcasecmp() Case-insensitive string comparison using a "natural order" algorithmstrnatcmp() String comparison using a "natural order" algorithmstrncasecmp() Binary safe case-insensitive string comparison of the first n charactersstrncmp() Binary safe string comparison of the first n charactersstrpbrk() Search a string for any of a set of charactersstrpos() Find position of first occurrence of a substring (case-sensitive)strrchr() Find the last occurrence of a character in a stringstrrev() Reverse a stringstrripos() Find position of last occurrence of a case-insensitive stringstrrpos() Find position of last occurrence of a substring (case-sensitive)strspn() Find length of initial segment matching maskstrstr() Find the first occurrence of a string (case-sensitive)strtok() Tokenize string (use explode() or preg_split() for more flexibility)strtolower() Make a string lowercase (use mb_strtolower() for multi-byte)strtoupper() Make a string uppercase (use mb_strtoupper() for multi-byte)strtr() Translate characters or replace substringssubstr() Return part of a string (use mb_substr() for multi-byte)substr_compare() Binary safe comparison of two strings from an offset, up to length characterssubstr_count() Count the number of substring occurrencessubstr_replace() Replace text within a portion of a stringtrim() Strip whitespace (or other characters) from the beginning and enducfirst() Make a string's first character uppercaseucwords() Uppercase the first character of each word in a stringvfprintf() Write a formatted string to a stream using an array of argumentsvprintf() Output a formatted string using an array of argumentsvsprintf() Return a formatted string using an array of argumentswordwrap() Wrap a string to a given number of charactersPassword Hashing: Never use md5(), sha1(), or crypt() directly for storing passwords. Always use the modern password_hash() function to create secure password hashes and password_verify() to check them.