08 Jul PHP String Handling
Strings are sequence of characters, which we also saw in the PHP Data types lesson. Here are some of the string operations:
- Length of a string
- Search a text within a string
- Concatenate two strings
- Reverse a string
PHP strlen() – Length of a String
The function strlen() returns the length of a string. In the below example, we’re finding the length of the word, Studyopedia!
The function returns the length and are printed using echo output statement,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <body> <?php echo "Length:"; echo strlen("Studyopedia!"); ?> </body> </html> |
Here’s the output,
PHP strpos() function – Search a Text within a String
With the string function strpos(), easily search a string or character within a string. On founding a match, the function returns the position of the 1st match, else it returns FALSE.
In the below example, we are searching for the first match of the word Kohli in the text Virat Kohli!,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html> <html> <body> <?php echo "String position: "; echo strpos("Virat Kohli!", "Kohli"); ?> </body> </html> |
Here’s the output,
PHP – Concatenate two Strings (.)
The dot operator (.) concatenates two strings together. Here’s an explanation that how the dot operator concatenates,
In the below example, we are concatenating Year with 2016, with the dot operator,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!DOCTYPE html> <html> <body> <?php $a = "Year"; $b = "2016"; echo $a . ": " . $b; ?> </body> </html> |
Here’s the output,
PHP strrev() function – Reverse a String
The function strrev() reverse the string. In the below example, we’re reversing the string john,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html> <body> <?php echo "john<br>"; echo "Reverse: "; echo strrev("john"); ?> </body> </html> |
Here’s the output,
More String Functions
We saw four string functions above. Now we will learn some more well-known functions.
The table is referred to from the official PHP website. For the complete list, refer to PHP.net
Function | Description |
---|---|
addcslashes() | Returns a string with backslashes in front of the specified characters |
addslashes() | Returns a string with backslashes in front of predefined characters |
bin2hex() | Converts a string of ASCII characters to hexadecimal values |
chop() | Removes whitespace or other characters from the right end of a string |
chr() | Returns a character from a specified ASCII value |
crypt() | One-way string hashing |
echo() | Outputs one or more strings |
explode() | Breaks a string into an array |
fprintf() | Writes a formatted string to a specified output stream |
get_html_translation_table() | Returns the translation table used by htmlspecialchars() and htmlentities() |
md5() | Calculates the MD5 hash of a string |
No Comments