PHP Strings

In this tutorial, learn about PHP strings and method to find the length, count the number of characters, replace text, reverse string, concatenate strings, and split a string into an array using PHP.

What is PHP String

PHP string is a sequence of characters that may contain letters, numbers, and special characters. You can create a string in PHP by placing the characters within the single or double quotes as given below:

Get Length of Strings in PHP

The length is the number of characters present in the string including spaces. To find the length of the string in PHP, you have to use the strlen() as given below:

Output

24

The above example shows that the length of the string is 24.

Count Number of Words in a Strings in PHP

To count the number of words in a string, you have to use the str_word_count() function of PHP and pass string variable as an argument.

Output

3

The output shows that there are 3 words in a string above.

Replace Text Content in a String Using PHP

You can replace the text content in a string with the new text of your choice. To replace the text content of a string, you have to use the str_replace() of PHP as given below:

Output

PHP with TutorialDeep!

The above example replaces “Learn” with “PHP”.

Reverse String

You can reverse the sequence of characters in a string. To reverse the string in PHP, you have to use the strrev() and pass the string variable as an argument.

Output

!peeDlairotuT htiw nraeL

The last character comes first after reversing the order of characters in a string.

Concatenate PHP Strings

Concatenation of PHP strings is the process of adding two or more strings together into a single string. To concatenate strings in PHP, you have to use the concatenation (.) operator as given below:

Output

Hello World!

The result of concatenation joins the two strings into a single string.

Search For a Text If String Contains

Output

11

The above example shows that the character position of the first match is 11.

Split String into an Array in PHP

Split a string into an array is the process of breaking the string into an array in PHP. To break the string into an array, you have to use the explode() function of PHP as given below:

Output

Array ( [0] => Welcome [1] => to [2] => TutorialDeep! )

You May Also Like to Read