About Lesson
How to define a string?
Strings can be written in single quotes or double quotes.
Example:
PHP
<?php
$str1 = 'Hello';
$str2 = "World";
echo $str1 . " " . $str2; // Outputs: Hello World
?>
What is string concatenation?
Concatenation joins two or more strings using the .
(dot) operator.
Example:
PHP
<?php
$first = "PHP";
$second = "Rocks";
echo $first . " " . $second; // Outputs: PHP Rocks
?>
Common String Functions
Function | Description | Example |
---|---|---|
strlen() | Returns length of a string | strlen("PHP") → 3 |
strtoupper() | Converts string to uppercase | "php" → "PHP" |
strtolower() | Converts string to lowercase | "PHP" → "php" |
ucfirst() | Capitalizes first character | "php" → "Php" |
strrev() | Reverses a string | "PHP" → "PHP" |
strpos() | Finds position of substring | "Hello", "e" → 1 |
str_replace() | Replaces text in a string | "World" → "PHP" |
trim() | Removes whitespace from both ends | " PHP " → "PHP" |
Example of string functions
PHP
<?php
$str = " Hello PHP World ";
echo strlen($str); // Length
echo strtoupper($str); // Uppercase
echo strtolower($str); // Lowercase
echo trim($str); // Remove spaces
echo str_replace("PHP", "Java", $str); // Replace PHP with Java
?>
Escape characters in strings
Use backslash \
to escape characters like quotes inside a string.
PHP
<?php
echo "She said: \"I love PHP!\"";
?>
: HEREDOC and NOWDOC
Used for writing long strings with multiple lines.
HEREDOC Example:
PHP
<?php
$text = <<<EOD
This is a long paragraph
spanning multiple lines in PHP.
EOD;
echo $text;
?>
NOWDOC Example:
PHP
<?php
$text = <<<'EOD'
This will not parse variables like $text
EOD;
echo $text;
?>