What is String in PHP?
A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all. The simplest way to create a string is to enclose the string literal (i.e. string characters) in single quotation marks (‘), like this:
Example: $my_string = ‘Hello World’;
You can also use double quotation marks (“). However, single and double quotation marks work in different ways. Strings enclosed in single-quotes are treated almost literally, whereas the strings delimited by the double quotes replaces variables with the string representations of their values as well as specially interpreting certain escape sequences.
The escape-sequence replacements are:
\n
is replaced by the newline character\r
is replaced by the carriage-return character\t
is replaced by the tab character\$
is replaced by the dollar sign itself ($
)\"
is replaced by a single double-quote ("
)\\
is replaced by a single backslash (\
)
Here’s an example to clarify the differences between single and double quoted strings:
Example:
Manipulating PHP Strings
PHP provides many built-in functions for manipulating strings like calculating the length of a string, find substrings or characters, replacing part of a string with different characters, take a string apart, and many others. Here are the examples of some of these functions.
Calculating the Length of a String
The strlen()
function is used to calculate the number of characters inside a string. It also includes the blank spaces inside the string.
Example:
outputs 24
Counting Number of Words in a String
The str_word_count()
function counts the number of words in a string.
Example:
outputs 9
Replacing Text within Strings
The str_replace()
replaces all occurrences of the search text within the target string.
Example:
outputs :- If the truth do not fit the theory, change the truth.
Reversing a String
The strrev()
function reverses a string.
Example:
outputs:- .gnihtyreve ton tub ,gnihtyna od nac uoY
Strpos() – Search For a Text Within a String
The PHP strpos()
the function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
Example:
outputs:- 6
- Top 10 Website Development Companies in Vadodara - December 20, 2024
- Compare SAST, DAST and RASP & its Tools for DevSecOps - December 19, 2024
- Comparing AWS, Azure, and Google Cloud in terms of services - December 19, 2024