In this tutorial, we will learn about Strings in PHP. A string is commonly described as a collection of characters. Mean a string is collection of number, alphabets or special symbols for example “Hello World”. In PHP you can define a string in the program with two ways by using single quotes(‘ ‘) or by using double(” “) quotes. Here we learn about strings, basic functions in strings, escape-sequence and difference between single and double quote string.
Differenene between Single and Double Quote Strings:
As I said we can write strings in PHP in both single and double-quotes. But there is a certain difference between both. If you write a string in single quotes it will take string literally. Suppose you have a variable $num=10; and if you write something like this ‘Value of num=$num’. In this case, it will show exactly the same. But if you will wite this in double-quotes the variable name will changed with its value. To understand it more clearly follow the given example.
<?php $num =10; echo 'value of num = $num'; echo "value of num = $num"; ?>
Escape-Sequence in strings:
These are some special escape sequence in PHP which we can use with strings. These escape sequences get replace with special values. Check these escape sequence.
- \n is replaced with the newline character.
- \\ is replaced with a single backslash. (\)
- \r is replaced with the carriage-return character.
- \t is replaced with the tab.
- \” is replaced with a single double-quote (“).
- \$ is replaced with the dollar sign itself ($).
Basic string Functions:
Here we will check some of the basic functions with would so helpful to you while working with strings. Here is like of some basic string functions in PHP.
- strlen() : function to check total number of characters in string.
- str_replace() : function to replace part or parts of string with other string.
- str_word_count() : function to check total number of words in string.
- strrev() : function to reverse string in PHP.