A string in PHP is a sequence of characters (text).
$name = "Aditya";
echo $name;
🔹 1. String Functions (Important Built-in Functions)
PHP provides many built-in functions to work with strings.
📌 Common String Functions
$str = "Hello World";// Length of string
echo strlen($str); // 11// Convert to lowercase
echo strtolower($str); // hello world// Convert to uppercase
echo strtoupper($str); // HELLO WORLD// First letter capital
echo ucfirst("hello"); // Hello// First letter of each word
echo ucwords("hello world"); // Hello World// Reverse string
echo strrev("Hello"); // olleH// Find position
echo strpos($str, "World"); // 6// Replace text
echo str_replace("World", "PHP", $str); // Hello PHP
🔹 2. String Manipulation
String manipulation means modifying or working with strings.
📌 Concatenation (Joining Strings)
$first = "Hello";
$second = "World";echo $first . " " . $second; // Hello World
📌 Substring
echo substr("Hello World", 0, 5); // Hello
📌 Trim (Remove Spaces)
$str = " Hello ";
echo trim($str); // "Hello"
📌 Compare Strings
if ("apple" == "apple") {
echo "Same";
}
🔹 3. Explode / Implode
These are very important for working with arrays and strings.
📌 explode() → String ➝ Array
Splits a string into an array.
$str = "apple,banana,mango";
$arr = explode(",", $str);print_r($arr);
👉 Output:
Array ( [0] => apple [1] => banana [2] => mango )
📌 implode() → Array ➝ String
Joins array elements into a string.
$arr = ["apple", "banana", "mango"];
$str = implode(",", $arr);echo $str; // apple,banana,mango
🔹 4. Regular Expressions (Regex)
Regex is used to match, search, or replace patterns in strings.
PHP uses functions like:
preg_match()preg_replace()preg_match_all()
📌 preg_match() (Check Pattern)
$str = "Hello123";if (preg_match("/[0-9]/", $str)) {
echo "Number found";
}
📌 preg_replace() (Replace Pattern)
$str = "Hello123";echo preg_replace("/[0-9]/", "", $str);
// Output: Hello
📌 preg_match_all() (Find All Matches)
$str = "abc123xyz456";preg_match_all("/[0-9]+/", $str, $matches);print_r($matches);
📌 Common Regex Patterns
| Pattern | Meaning |
|---|---|
/[0-9]/ | Any number |
/[a-z]/ | Lowercase letters |
/[A-Z]/ | Uppercase letters |
/^[a-z]+$/ | Only lowercase letters |
/^\d+$/ | Only numbers |
/^[a-zA-Z0-9]+$/ | Alphanumeric |
🎯 Real Example (Form Validation)
$email = "test@gmail.com";if (preg_match("/^[\w\.-]+@[\w\.-]+\.\w+$/", $email)) {
echo "Valid Email";
} else {
echo "Invalid Email";
}
🚀 Summary
- String Functions → Ready-made tools (strlen, strtoupper, etc.)
- String Manipulation → Modify strings (concat, substr, trim)
- explode() / implode() → Convert between string ↔ array
- Regex → Advanced pattern matching & validation






