PHP Strings — Complete Guide to String Manipulation, Functions, and Patterns
In this tutorial, you will learn about PHP Strings. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP strings are sequences of characters that support single and double quotes, heredoc/nowdoc syntax, and a rich set of built-in functions for manipulation and searching.
What You'll Learn
By the end of this tutorial, you'll use string quoting, concatenation, heredoc, search/replace functions, regex patterns, formatting, and multi-byte string handling.
Why PHP Strings Matter
PHP was designed for web development where strings are everywhere: HTML output, URL parameters, JSON payloads, database queries, and user input. String functions are used in almost every PHP script.
Real-World Use
A content management system uses PHP string functions to sanitize user input, generate slugs from titles, truncate article previews, and format dates for display.
PHP Strings Learning Path
flowchart LR
A[Types] --> B[Strings]
B --> C[Numbers]
C --> D[Operators]
D --> E[Control Flow]
A --> F{You Are Here}
style F fill:#f90,color:#fff
String Quotes
<?php
$name = "Alice";
echo 'Hello, $name'; // Hello, $name (literal)
echo "Hello, $name"; // Hello, Alice (interpolated)
echo "Length: " . strlen("Hello"); // 5
Heredoc and Nowdoc
<?php
$name = "Alice";
$html = <<<HTML
<div>
<h1>Welcome, $name</h1>
<p>This is heredoc syntax.</p>
</div>
HTML;
echo $html;
String Functions
<?php
$text = " Hello World! ";
echo strlen($text); // 17
echo trim($text); // "Hello World!"
echo strtoupper($text); // " HELLO WORLD! "
echo strtolower($text); // " hello world! "
echo ucfirst("hello"); // "Hello"
echo substr("Hello", 1, 3); // "ell"
Search and Replace
<?php
$text = "The quick brown fox";
echo strpos($text, "quick"); // 4 (position)
echo str_replace("fox", "dog", $text); // The quick brown dog
echo substr_replace($text, "fast", 4, 5); // The fast brown fox
String Formatting
<?php
printf("Hello %s, you have %d new messages", "Alice", 5);
// Hello Alice, you have 5 new messages
$formatted = sprintf("Price: $%.2f", 19.5); // Price: $19.50
echo number_format(1234567.89, 2); // 1,234,567.89
Regular Expressions
<?php
$email = "user@example.com";
if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
echo "Valid email";
}
$replaced = preg_replace("/\s+/", "-", "Hello World PHP"); // Hello-World-PHP
Common Mistakes
1. Forgetting Single Quotes Don't Interpolate
Variables in single quotes are literal. Use double quotes or concatenation when you need variable values.
2. SQL Injection via String Interpolation
Never embed variables directly in SQL strings. Use prepared statements.
3. Not Handling Multi-Byte Characters
strlen("cafe") returns 4 but strlen("cafe") with accented characters returns more. Use mb_strlen() for UTF-8.
4. Confusing strpos Return Value
strpos returns false (0) when needle is not found, but 0 is also a valid position. Always check === false.
5. Using Regular Expressions for Simple Operations
str_replace is faster than preg_replace for simple string replacements. Use regex only when pattern matching is needed.
Practice Questions
1. What is the difference between single and double quotes?
Double quotes interpolate variables and escape sequences (\n, \t). Single quotes are literal with only \ and ' escaped.
2. What does trim() do?
It removes whitespace (spaces, tabs, newlines) from the beginning and end of a string.
3. How do you check if a string contains a substring in PHP 8+?
Use str_contains($haystack, $needle). Returns true/false. More readable than strpos.
4. What is the difference between echo and print_r?
echo outputs one or more strings. print_r prints human-readable information about a variable, including arrays and objects.
5. Challenge: Write a function that generates a URL-friendly slug from a string.
<?php
function slugify(string $text): string {
$text = strtolower(trim($text));
$text = preg_replace("/[^a-z0-9]+/", "-", $text);
return trim($text, "-");
}
echo slugify("Hello World! How are you?"); // hello-world-how-are-you
FAQ
Mini Project: Text Processor
Build a text processing utility that sanitizes, truncates, and formats user-submitted content.
<?php
function processText(string $text, int $maxLength = 200): array {
$sanitized = htmlspecialchars(strip_tags($text));
$truncated = strlen($sanitized) > $maxLength
? substr($sanitized, 0, $maxLength) . "..."
: $sanitized;
$words = str_word_count($sanitized);
return [
"original" => $text,
"sanitized" => $sanitized,
"preview" => $truncated,
"wordCount" => $words,
"charCount" => strlen($sanitized)
];
}
print_r(processText("<b>Hello</b> World! This is a long text...", 20));
What's Next
PHP Numbers PHP Operators PHP Arrays
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro