PHP String Handling

PHP String Handling

Strings are sequence of characters, which we also saw in the PHP Data types lesson. Here are some of the PHP string functions used for string operations,

Length of a String – PHP strlen

The function strlen() returns the length of a string. In the below example, we’re finding the length of the word, Studyopedia!

The functions returns the length and is printed using echo output statement,

Here’s the output,

strlen PHP string function

Search a String/ Text within a String – PHP strpos function

With the string function strpos(), you can 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!,

Here’s the output,
strpos PHP string function

Concatenate a String (.)

The dot operator (.) concatenates two strings together. Here’s an explanation that how the dot operator concatenates,

Concatenating strings in PHP

 

Here, we are concatenating Year with 2016, with the dot operator,

Here’s the output,

PHP String Concatenation

Reverse a String – PHP strrev function

The function strrev() reverse the string. Here, we’re reversing the string john,

Here’s the output,

strrev PHP string function

More String Functions

We saw four string functions above. Now we will learn some more well-known functions.

The table is referred from the official PHP website. For complete list, refer PHP.net

FunctionDescription
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

PHP Arrays
PHP GET Method
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create free tutorials for all.

No Comments

Post A Comment