PHP String Manipulation (Step-by-Step Guide with Examples)
PHP string manipulation allows developers to modify, format, and process text dynamically. Whether you’re working with user inputs, database queries, or content generation, mastering PHP string functions is crucial for writing efficient code.
1. Declaring and Printing Strings in PHP
<?php
// Using double quotes
$string1 = "Hello, PHP!";
// Using single quotes
$string2 = 'Welcome to PHP!';
// Printing a string
echo $string1;
?>
✅ Tip:
- Double quotes allow variable interpolation (
$var inside string
gets replaced). - Single quotes do not process variables.
2. String Concatenation
Using .
Operator
<?php
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo $fullName; // Output: John Doe
?>
✅ Tip: Use .=
for appending strings.
<?php
$text = "Hello";
$text .= " World!";
echo $text; // Output: Hello World!
?>
3. Changing Case in Strings
Convert to Uppercase (strtoupper
)
<?php
$text = "php is awesome!";
echo strtoupper($text); // Output: PHP IS AWESOME!
?>
Convert to Lowercase (strtolower
)
<?php
$text = "HELLO PHP!";
echo strtolower($text); // Output: hello php!
?>
Capitalize First Letter (ucfirst
)
<?php
$text = "php is great!";
echo ucfirst($text); // Output: Php is great!
?>
Capitalize Each Word (ucwords
)
<?php
$text = "php is fun!";
echo ucwords($text); // Output: Php Is Fun!
?>
4. Extracting Parts of a String
Using substr()
to Get a Substring
<?php
$text = "Hello, PHP!";
echo substr($text, 7, 3); // Output: PHP
?>
✅ Tip:
substr($text, 0, 5)
→ Extracts first 5 characterssubstr($text, -3)
→ Extracts last 3 characters
5. Finding and Replacing Text
Finding a Substring (strpos
)
<?php
$text = "Welcome to PHP!";
echo strpos($text, "PHP"); // Output: 11
?>
Replacing Text (str_replace
)
<?php
$text = "Hello, World!";
$newText = str_replace("World", "PHP", $text);
echo $newText; // Output: Hello, PHP!
?>
✅ Tip: Use str_ireplace()
for case-insensitive replacement.
Best Practices for PHP String Manipulation
✔️ Use trim()
to clean up user input
✔️ Use str_replace()
for simple replacements, preg_replace()
for advanced cases
✔️ Use strpos()
to check if a string contains a keyword
✔️ Always escape strings (htmlspecialchars()
) when handling user input