A string is a sequence of characters, like "Hello world!". In PHP, strings are one of the most frequently used data types. Mastering how to search, modify, and format text is essential for building dynamic web applications.
PHP comes with hundreds of built-in functions to manipulate strings. Here are the most commonly used ones:
The strlen() function returns the length of a string (the number of characters).
<?php
echo strlen("Hello world!"); // Outputs: 12
?>
The str_word_count() function counts the number of words in a string.
<?php
echo str_word_count("Hello world!"); // Outputs: 2
?>
The strrev() function reverses a string.
<?php
echo strrev("Hello world!"); // Outputs: !dlrow olleH
?>
The strpos() function searches for a specific text within a string. If a match is found, it returns the character position of the first match. If no match is found, it returns FALSE.
<?php
echo strpos("Hello world!", "world"); // Outputs: 6
?>
The str_replace() function replaces some characters with other characters in a string.
<?php
echo str_replace("world", "Dolly", "Hello world!"); // Outputs: Hello Dolly!
?>
You can use either single quotes or double quotes for strings, but there is a major difference in how PHP treats them:
<?php
$name = "Alice";
echo "Hello $name"; // Outputs: Hello Alice
echo 'Hello $name'; // Outputs: Hello $name
?>
Sometimes you need to include characters that would otherwise break your string (like quotes) or add formatting like new lines. You can do this using the backslash \.
| Character | Result |
|---|---|
\" |
Double Quote |
\' |
Single Quote |
\$ |
PHP Variable Sign (prevents interpolation) |
\n |
New Line (visible in source code) |
\t |
Tab |
<?php
$x = "The world's \"best\" developer is you.";
echo $x;
?>
.).
\) to escape special characters like quotes or dollar signs..).