String Handling in PHP – Working with Text
What is a String in PHP?
A string is a sequence of characters used to represent text in PHP. It can include letters, numbers, symbols, or even spaces.
Strings are one of the most commonly used data types in PHP — whether you’re printing messages, validating form input, creating email templates, or building APIs.
Declaring Strings in PHP
Strings can be declared using:
- Single quotes (
'
) – Faster but doesn’t parse variables - Double quotes (
"
) – Parses variables and escape sequences
Example:
$name = 'Jay';
echo 'Hello $name'; // Output: Hello $name
echo "Hello $name"; // Output: Hello Jay
Concatenation – Joining Strings in PHP
You can join strings using the dot (.
) operator.
Example:
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo $fullName; // Output: John Doe
Concatenation with .=
$message = "Hello";
$message .= ", world!";
echo $message; // Output: Hello, world!
Common String Functions in PHP
PHP offers many built-in string functions for manipulation. Here are the most frequently used:
1. strlen()
– String Length
echo strlen("ScriptBuzz"); // Output: 10
2. strtoupper()
and strtolower()
echo strtoupper("php"); // Output: PHP
echo strtolower("SCRIPT"); // Output: script
3. ucfirst()
and ucwords()
echo ucfirst("jay"); // Output: Jay
echo ucwords("jay patel"); // Output: Jay Patel
4. substr()
– Extract a part of a string
echo substr("ScriptBuzz", 0, 6); // Output: Script
5. str_replace()
– Replace text in a string
echo str_replace("world", "PHP", "Hello world"); // Output: Hello PHP
6. strpos()
– Find position of substring
echo strpos("Learn PHP at ScriptBuzz", "PHP"); // Output: 6
Multiline Strings – Heredoc & Nowdoc
When working with blocks of text, use Heredoc or Nowdoc.
Heredoc (supports variables):
$name = "Jay";
$text = <<<EOD
Hello $name,
Welcome to ScriptBuzz!
EOD;
echo $text;
Nowdoc (treats as plain text):
$text = <<<'EOD'
This is plain text. No variables will be parsed.
EOD;
Trimming and Cleaning Strings
trim()
– Removes whitespace from both ends
$name = " Jay ";
echo trim($name); // Output: Jay
ltrim()
and rtrim()
echo ltrim(" hello"); // Removes left spaces
echo rtrim("hello "); // Removes right spaces
Real-World Examples of String Handling
1. Format Full Name
$first = "john";
$last = "DOE";
$full = ucwords(strtolower($first . " " . $last));
echo $full; // Output: John Doe
2. Mask an Email Address
$email = "hello@example.com";
$hidden = substr($email, 0, 2) . "****" . strstr($email, "@");
echo $hidden; // Output: he****@example.com
3. Validate if String Contains a Keyword
$input = "I love PHP programming"; if (strpos($input, "PHP") !== false) { echo "You're a PHP developer!"; }
Common Mistakes with Strings
- Using single quotes when you want variable interpolation
- Forgetting that
strpos()
returns0
for the first position (not false!) - Not trimming user input before saving or comparing
- Confusing string functions with similar names (
strstr()
vsstrpos()
)
Best Practices
- Use
trim()
on user-submitted form data - Use double quotes only when necessary (to improve performance)
- Combine multiple string functions for formatting
- Validate and sanitize strings before using them in queries or output
- Escape special characters for HTML using
htmlspecialchars()
Notes:
- Strings are used to store and manipulate textual data in PHP
- You can concatenate strings using
.
, and include variables with double quotes - PHP offers powerful functions to work with, format, and search strings
- Clean and trim inputs to ensure reliability
- Heredoc/Nowdoc help with multiline string output
Practice Tasks
Task 1: Welcome Message Generator
Create a function that takes a name and returns:
Hello, [Name]! Your name has [X] letters.
Task 2: Case Converter
Take a sentence and:
- Convert to lowercase
- Convert to uppercase
- Capitalize first letter of each word
Task 3: Password Masking
Create a function that replaces all but the last 3 characters of a string with *
.
Example: secretpassword
→ *********ord
💡 Explore More PHP Learning Tools & Resources
PHP Practice Quiz
Test your PHP skills with real coding questions and scoring.
PHP Interview Questions
Prepare for interviews with common PHP questions and answers.
Educational AI Tutor
Ask PHP questions and get instant AI-powered explanations.
Question Generator
Auto-generate PHP interview questions for quick practice.