5) Strings

What is String in PHP?

A string in PHP is a sequence of letters, characters, numbers, special characters and arithmetic values or it can be a combination of all. To create a string simply enclose the string in single quotation marks (‘)
Example

You can also use double quotation marks (“). However, there is s difference between how it works as explained earlier here.

Some String Function examples

1) Calculate Length of a String

The strlen() function is used to find the number of characters inside a string. along with blank spaces inside the string.

Example:

2) Count Number of Words in a String

The function str_word_count() counts the number of words in a string.

Example

3) Replace Text within Strings

The str_replace() replaces all occurrences of the search text within the target string.

Example:

You can always check the official website for all the string functions:

List of all string functions

Using heredoc syntax

Why use heredoc: Before learning what is heredoc I would like you to understand the need for heredoc.
Let’s understand it by taking an example of a string that contains a lot of quotation mark

Here we need to escape double quotes everytime we want to use it. It looks ugly and messy and difficult to manage also. To avoid this you can build a string using heredoc syntax. Inside heredoc, all double quotes and single quotes are interpreted correctly.

Note: there has to be nothing after EOT, not even space.