About Lesson
PHP String Functions
1. strlen():
Returns the length of a string (number of characters, including spaces).
Example:
PHP
<?php
$text = "Hello World!";
echo "Length: " . strlen($text);
?>
Output: Length: 12
2. str_replace():
Replaces every occurrence of a word or character with another.
Example:
PHP
<?php
$text = "I like apples.";
$newText = str_replace("apples", "mangoes", $text);
echo $newText;
?>
Output: I like mangoes.
3. substr()
:
Returns a portion of a string.
Syntax: substr(string, start, length)
Example:
PHP
<?php
$text = "Hello World!";
echo substr($text, 0, 5); // From index 0 → 5 characters
echo "<br>";
echo substr($text, 6); // From index 6 till end
?>
Output: Array ( [0] => red [1] => blue [2] => green [3] => yellow )
4. strpos():
Finds where the substring first appears in the string.
Example:
PHP
<?php
$text = "Hello World!";
$pos = strpos($text, "World");
if ($pos !== false) {
echo "Found at position: " . $pos;
}
?>