A string is a sequence of characters, like “Hello world!”.. PHP has over 75 built-in String manipulation functions, supporting operations ranging from string repetition and reversal to comparison and search-and-replace.
Some of these important functions are
- empty() – Tests if a string is empty
- strlen() – Calculates the number of characters in a string
- strrev() – Retrun reverse of a given string
- str_repeat() – Repeats a string no. of times you want
- substr() – Retrieves a section of a string
- strcmp() – Compares two strings
- str_word_count() – Calculates the number of words in a string
- str_replace() – Replaces parts of a string
- trim() – removes leading and trailing whitespaces from a string
- strtolower() – Converts in Lowercases a string
- strtoupper() – Converts in Uppercases a string
- ucfirst() – Converts in uppercase the first character of a string
- ucwords() – Converts in uppercases the first character of every word of a string
- addslashes() – Escapes special characters in a string with backslashes
- stripslashes() – Removes backslashes from a string
- htmlentities() – Encodes HTML within a string
- htmlspecialchars() – Encodes special HTML characters within a sting
- nl2br() – Replaces line breaks in a string with elements
- html_entity_decode() – Decodes HTML entities within a string
- htmlspecialchars_decode() – Decodes special HTML characters withing a string
- strip_tags() – Removes PHP and HTML code from a string
- md5() – The MD5 message-digest algorithm is a widely used for cryptography
- wordwrap – Wraps a string to a given number of characters
- print – Output a string
- printf – Output a formatted string
Click here to find the complete list of String Functions in PhP
Example to get the Length of the String
The PHP strlen() function returns the length of a string.
<?php echo strlen("Hello world!"); ?>
Output: 12
Example to Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string. Example is to replaces the text “world” with “Dolly”
<?php echo str_replace("world", "Dolly", "Hello world!"); ?>
Output: Hello Dolly!
Example to Count The Number of Words in a String
The PHP str_word_count() function counts the number of words in a string
<?php echo str_word_count("Hello world!"); ?
Output: 2