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,

Here’s the output,

strlen PHP string function

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!,

Here’s the output,
strpos PHP string function

PHP – Concatenate two Strings (.)

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

Concatenating strings in PHP


In the below example, we are concatenating Year with 2016, with the dot operator,

Here’s the output,

PHP String Concatenation

PHP strrev() function – Reverse a String

The function strrev() reverse the string. In the below example, 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 to from the official PHP website. For the complete list, refer to

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 Decision Making Statements
PHP GET Method
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading