1. Single Quotes vs Double Quotes
PHP handles single-quoted ('...') and double-quoted ("...") strings differently:
- Single Quotes: Treat strings literally. Variables and escape sequences (except
\'and\\) are not parsed. - Double Quotes: Evaluate variable interpolation and escape sequences such as
\n,\t, and\$.
'; // Outputs: I am studying $subject.
echo "I am studying $subject.
"; // Outputs: I am studying PHP.
2. String Concatenation
Strings in PHP are concatenated using the period (.) operator, while .= appends onto an existing string:
3. Essential Built-in String Functions
| Function | Description | Example |
|---|---|---|
strlen($str) |
Returns string length (byte count). | strlen("Hello") // 5 |
str_word_count($str) |
Counts words in a string. | str_word_count("Online CBT") // 2 |
strtoupper($str) / strtolower($str) |
Converts case to uppercase or lowercase. | strtolower("ADMIN") // admin |
strpos($haystack, $needle) |
Finds position of first occurrence (0-indexed). | strpos("CBT Test", "Test") // 4 |
str_replace($search, $replace, $subject) |
Replaces all occurrences of search string. | str_replace("red", "blue", "red car") |
substr($str, $start, $length) |
Extracts substring from starting index. | substr("Certificate", 0, 4) // Cert |
trim($str) |
Strips whitespace from beginning and end. | trim(" user input ") |
4. Splitting and Joining: explode() and implode()
5. Security: Escaping HTML Output
Whenever outputting user-supplied strings onto a web page, you must prevent Cross-Site Scripting (XSS) by using htmlspecialchars():
alert('Hacked!');";
// Safe rendering: converts < to < and > to >
echo htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');