Strings & String Functions
Strings are one of the most commonly used data types in PHP. In this lesson, we'll explore how to create, manipulate, and transform strings using PHP's powerful built-in functions.
Creating Strings
PHP provides multiple ways to create strings:
<?php
// Single quotes - literal strings
$name = 'John Doe';
$path = 'C:\xampp\htdocs'; // No escape needed
// Double quotes - interprets variables and escape sequences
$greeting = "Hello, $name";
$message = "Welcome\nTo PHP"; // \n is newline
// Curly braces for complex variables
$user = ['name' => 'John'];
echo "User: {$user['name']}";
// Heredoc - multi-line strings with parsing
$html = <<<HTML
<div class="container">
<h1>Welcome $name</h1>
<p>This is a multi-line string</p>
</div>
HTML;
// Nowdoc - multi-line strings without parsing (like single quotes)
$code = <<<'CODE'
<?php
echo "This won't be parsed: $variable";
?>
CODE;
?>
Best Practice: Use single quotes for static strings (faster). Use double quotes only when you need variable interpolation or escape sequences.
Escape Sequences
Special characters in double-quoted strings:
Common Escape Sequences:
\n - Newline
\r - Carriage return
\t - Tab
\\ - Backslash
\" - Double quote
\$ - Dollar sign (prevent variable parsing)
\' - Single quote (needed in single-quoted strings)
Examples:
<?php
echo "Line 1\nLine 2"; // Two lines
echo "Name:\tJohn"; // Tab between Name: and John
echo "Price: \$19.99"; // Literal dollar sign
echo 'It\'s a beautiful day'; // Escaped single quote
?>
String Concatenation
Combining strings using the dot (.) operator:
<?php
$firstName = "John";
$lastName = "Doe";
// Basic concatenation
$fullName = $firstName . " " . $lastName;
// Concatenation with assignment
$message = "Hello";
$message .= ", ";
$message .= $firstName;
// Multiple concatenations
$html = "<div>" .
"<h1>" . $fullName . "</h1>" .
"<p>Welcome!</p>" .
"</div>";
// Mixed with other types
$age = 25;
$info = "Name: " . $fullName . ", Age: " . $age;
?>
String Length
Get the number of characters in a string:
<?php
$text = "Hello World";
$length = strlen($text);
echo $length; // Output: 11
// Practical use: validation
$password = "abc123";
if (strlen($password) < 8) {
echo "Password must be at least 8 characters";
}
// Multi-byte strings (UTF-8)
$arabic = "مرحبا";
echo strlen($arabic); // Byte count (may be wrong)
echo mb_strlen($arabic); // Character count (correct)
?>
Important: Use mb_strlen() for multi-byte characters (Arabic, Chinese, emojis) instead of strlen() to get accurate character counts.
Case Conversion
Change the case of strings:
<?php
$text = "Hello World";
// Convert to lowercase
echo strtolower($text); // Output: hello world
// Convert to uppercase
echo strtoupper($text); // Output: HELLO WORLD
// Capitalize first letter
echo ucfirst($text); // Output: Hello world
// Capitalize first letter of each word
echo ucwords($text); // Output: Hello World
// Lowercase first letter
echo lcfirst("Hello"); // Output: hello
// Practical use: email normalization
$email = "JohnDoe@EXAMPLE.COM";
$normalized = strtolower($email); // johndoe@example.com
?>
Trimming Whitespace
Remove whitespace from the beginning and/or end of strings:
<?php
$text = " Hello World ";
// Remove from both sides
echo trim($text); // "Hello World"
// Remove from left side only
echo ltrim($text); // "Hello World "
// Remove from right side only
echo rtrim($text); // " Hello World"
// Remove specific characters
$url = "///example.com///";
echo trim($url, "/"); // "example.com"
// Practical use: clean user input
$username = trim($_POST['username'] ?? '');
?>
Best Practice: Always trim user input from forms to remove accidental spaces that users might enter.
Finding Substrings
Search for text within strings:
<?php
$text = "Hello World, Welcome to PHP World";
// Find first occurrence (returns position or false)
$pos = strpos($text, "World");
echo $pos; // Output: 6
// Find last occurrence
$lastPos = strrpos($text, "World");
echo $lastPos; // Output: 32
// Case-insensitive search
$pos = stripos($text, "world");
echo $pos; // Output: 6
// Check if string contains substring
if (strpos($text, "PHP") !== false) {
echo "Found PHP";
}
// PHP 8+ (recommended)
if (str_contains($text, "PHP")) {
echo "Found PHP";
}
// Starts with / Ends with (PHP 8+)
if (str_starts_with($text, "Hello")) {
echo "Starts with Hello";
}
if (str_ends_with($text, "World")) {
echo "Ends with World";
}
?>
Important: Always use !== false when checking strpos() results, because position 0 evaluates to false in a boolean context.
Extracting Substrings
Get portions of a string:
<?php
$text = "Hello World";
// Extract from position to end
echo substr($text, 6); // "World"
// Extract with length
echo substr($text, 0, 5); // "Hello"
// Negative offset (from end)
echo substr($text, -5); // "World"
// Negative length (exclude from end)
echo substr($text, 0, -6); // "Hello"
// Extract middle portion
echo substr($text, 3, 5); // "lo Wo"
// Practical use: truncate text
$description = "This is a very long description...";
$short = substr($description, 0, 50) . "...";
?>
Replacing Text
Find and replace text within strings:
<?php
$text = "Hello World";
// Replace all occurrences
echo str_replace("World", "PHP", $text);
// Output: Hello PHP
// Case-insensitive replace
echo str_ireplace("world", "PHP", $text);
// Output: Hello PHP
// Multiple replacements
$text = "I like apples and oranges";
$search = ["apples", "oranges"];
$replace = ["bananas", "grapes"];
echo str_replace($search, $replace, $text);
// Output: I like bananas and grapes
// Count replacements
$count = 0;
$result = str_replace("a", "X", "banana", $count);
echo $result; // Output: bXnXnX
echo $count; // Output: 3
// Replace first occurrence only
$text = "foo bar foo bar";
echo preg_replace('/foo/', 'baz', $text, 1);
// Output: baz bar foo bar
?>
Splitting and Joining Strings
Convert between strings and arrays:
<?php
// Split string into array
$text = "apple,banana,orange";
$fruits = explode(",", $text);
print_r($fruits);
// Array([0]=>apple [1]=>banana [2]=>orange)
// Join array into string
$joined = implode(", ", $fruits);
echo $joined; // Output: apple, banana, orange
// Alternative: join() (alias of implode)
echo join(" - ", $fruits);
// Split with limit
$text = "a:b:c:d:e";
$parts = explode(":", $text, 3);
// Array([0]=>a [1]=>b [2]=>c:d:e)
// Practical use: parse CSV
$csv = "John,Doe,john@example.com";
list($firstName, $lastName, $email) = explode(",", $csv);
?>
Remember: explode() creates array from string. implode() creates string from array. Think: "explode" breaks apart, "implode" brings together.
String Comparison
Compare strings in various ways:
<?php
$str1 = "apple";
$str2 = "Apple";
$str3 = "banana";
// Case-sensitive comparison
echo strcmp($str1, $str2); // > 0 (different case)
echo strcmp($str1, $str1); // 0 (equal)
echo strcmp($str1, $str3); // < 0 (apple before banana)
// Case-insensitive comparison
echo strcasecmp($str1, $str2); // 0 (same ignoring case)
// Natural order comparison (human-friendly)
$files = ["file10.txt", "file2.txt", "file1.txt"];
usort($files, "strnatcmp");
// Result: file1.txt, file2.txt, file10.txt
// Compare first n characters
echo strncmp("hello", "help", 3); // 0 ("hel" equals "hel")
?>
String Formatting
Format strings with placeholders:
<?php
// sprintf - return formatted string
$name = "John";
$age = 25;
$text = sprintf("Name: %s, Age: %d", $name, $age);
echo $text; // Output: Name: John, Age: 25
// printf - echo formatted string
printf("Name: %s, Age: %d", $name, $age);
// Common format specifiers:
// %s - string
// %d - integer
// %f - float
// %b - binary
// %x - hexadecimal
// Format decimal places
$price = 19.9567;
echo sprintf("Price: $%.2f", $price);
// Output: Price: $19.96
// Padding
echo sprintf("%05d", 42); // Output: 00042
echo sprintf("%-10s", "test"); // Output: "test "
?>
HTML and URL Functions
Handle HTML and URLs safely:
<?php
// HTML special characters
$text = "<script>alert('XSS')</script>";
echo htmlspecialchars($text);
// Output: <script>alert('XSS')</script>
// Strip HTML tags
$html = "<p>Hello <b>World</b></p>";
echo strip_tags($html); // Output: Hello World
echo strip_tags($html, '<b>'); // Output: Hello <b>World</b>
// URL encoding
$query = "search term with spaces";
echo urlencode($query);
// Output: search+term+with+spaces
// URL decoding
$encoded = "search%20term";
echo urldecode($encoded); // Output: search term
// Raw URL encoding (for URLs, not query strings)
echo rawurlencode("path/to/file name.txt");
// Output: path%2Fto%2Ffile%20name.txt
?>
Security: Always use htmlspecialchars() when displaying user-generated content in HTML to prevent XSS attacks!
Other Useful String Functions
<?php
// Reverse a string
echo strrev("Hello"); // Output: olleH
// Repeat a string
echo str_repeat("*", 10); // Output: **********
// Shuffle string characters
echo str_shuffle("Hello"); // Output: random order
// Count substring occurrences
$text = "Hello World, Welcome to PHP World";
echo substr_count($text, "World"); // Output: 2
// Word count
echo str_word_count("Hello World"); // Output: 2
// Number formatting
echo number_format(1234567.89); // 1,234,568
echo number_format(1234567.89, 2); // 1,234,567.89
echo number_format(1234567.89, 2, '.', ',');
// 1,234,567.89
// Parse string to variables
parse_str("name=John&age=25", $data);
print_r($data);
// Array([name]=>John [age]=>25)
?>
Multi-byte String Functions
For international character support (UTF-8):
<?php
$text = "مرحباً بك في PHP";
// Multi-byte string length
echo mb_strlen($text);
// Multi-byte substring
echo mb_substr($text, 0, 5);
// Multi-byte case conversion
echo mb_strtoupper($text);
echo mb_strtolower($text);
// Multi-byte strpos
echo mb_strpos($text, "PHP");
// Set default encoding
mb_internal_encoding("UTF-8");
?>
Practice Exercise:
Task: Create a string manipulation script that:
- Defines a sentence: " PHP is a POWERFUL server-side language "
- Trims whitespace
- Converts to title case (first letter of each word uppercase)
- Counts the number of words
- Replaces "PHP" with "PHP 8"
- Extracts the first 20 characters
- Displays all results
Solution:
<?php
// Original string
$sentence = " PHP is a POWERFUL server-side language ";
// Trim whitespace
$trimmed = trim($sentence);
echo "<p>Trimmed: '$trimmed'</p>";
// Convert to title case
$titleCase = ucwords(strtolower($trimmed));
echo "<p>Title Case: $titleCase</p>";
// Count words
$wordCount = str_word_count($titleCase);
echo "<p>Word Count: $wordCount</p>";
// Replace PHP with PHP 8
$replaced = str_replace("Php", "PHP 8", $titleCase);
echo "<p>Replaced: $replaced</p>";
// Extract first 20 characters
$excerpt = substr($replaced, 0, 20);
echo "<p>First 20 chars: $excerpt...</p>";
// Display length
echo "<p>Length: " . strlen($replaced) . " characters</p>";
?>
Summary
In this lesson, you learned:
- Create strings using single quotes, double quotes, heredoc, and nowdoc
- Use strlen() and mb_strlen() to get string length
- Convert case with strtolower(), strtoupper(), ucfirst(), ucwords()
- Trim whitespace with trim(), ltrim(), rtrim()
- Search strings with strpos(), stripos(), str_contains()
- Extract substrings with substr()
- Replace text with str_replace(), str_ireplace()
- Split and join with explode() and implode()
- Format strings with sprintf() and printf()
- Handle HTML safely with htmlspecialchars()
- Use multi-byte functions for international characters
Great Progress! You've completed Module 1: PHP Basics & Environment Setup. You now understand PHP syntax, variables, operators, and strings. Next, we'll dive into control structures like if-else, loops, and functions!