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
1 |
$my_string = 'Hello World'; |
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:
1 2 3 |
<?php echo strlen("Hello World"); // Output 11 ?> |
2) Count Number of Words in a String
The function str_word_count() counts the number of words in a string.
Example
1 2 3 |
<?php echo str_word_count("Welcome to codedecode!"); // outputs 3 ?> |
3) Replace Text within Strings
The str_replace() replaces all occurrences of the search text within the target string.
Example:
1 |
echo str_replace("world", "Kritika", "Hello world!"); // outputs Hello Kritika! |
You can always check the official website for all the 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
1 2 3 4 5 6 |
<?php $title = "Learning PHP is fun"; $author = "Kritika Shrivastava"; $statement = "In \"$title\" by $author the \"Power of mind is explained\""; echo $statement; ?> |
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.
1 2 3 4 5 6 |
$title = "Learning PHP is fun"; $author = "Kritika Shrivastava"; $heredoc = <<<EOT In "$title" by $author the "Power of mind is explained"; EOT; echo $heredoc; |