1. Introduction
Strings and Regular Expressions (RegEx) are essential in PHP for handling and manipulating text. Strings store sequences of characters, while regular expressions provide powerful pattern-matching capabilities.
2. PHP String Functions
PHP provides built-in functions to manipulate strings effectively.
2.1 Creating Strings
Example
<?php
$str1 = “Hello, World!”; // Double-quoted string
$str2 = ‘PHP Strings’; // Single-quoted string
echo $str1;
?>
📌 Difference Between Single and Double Quotes
- Single Quotes (‘): Treats content literally (\n is not interpreted).
- Double Quotes (“): Allows variable interpolation and escape sequences (\n for new line).
<?php
$name = “Alice”;
echo “Hello, $name”; // Output: Hello, Alice
echo ‘Hello, $name’; // Output: Hello, $name (No interpolation)
?>
2.2 Important String Functions
Function | Description | Example |
strlen() | Get length of string | strlen(“Hello”) → 5 |
strtoupper() | Convert to uppercase | “php” → “PHP” |
strtolower() | Convert to lowercase | “HELLO” → “hello” |
substr() | Extract substring | substr(“Hello”, 0, 3) → “Hel” |
strpos() | Find position of substring | strpos(“hello world”, “world”) → 6 |
str_replace() | Replace text in string | str_replace(“world”, “PHP”, “hello world”) → “hello PHP” |
trim() | Remove spaces from beginning & end | trim(” hello “) → “hello” |
explode() | Split string into an array | explode(“,”, “apple,banana,grape”) |
implode() | Join array elements into a string | implode(“-“, [“apple”, “banana”]) → “apple-banana” |
Example Usage
<?php
$str = ” Hello, PHP! “;
echo strlen($str); // Output: 14
echo trim($str); // Output: “Hello, PHP!”
echo strtoupper($str); // Output: ” HELLO, PHP! “
?>
3. Regular Expressions in PHP
3.1 Introduction to Regular Expressions
Regular expressions (RegEx) are used to search, validate, and manipulate strings based on patterns.
PHP provides two main functions for handling RegEx:
- preg_match() → Checks if a pattern exists in a string.
- preg_replace() → Replaces text that matches a pattern.
- preg_match_all() → Finds all matches.
📌 Basic Syntax
- /pattern/ → Defines a regular expression.
- /pattern/i → Case-insensitive match.
- /pattern/g → Global match (all occurrences).
3.2 Special Characters in RegEx
Character | Description | Example |
. | Matches any character except new line | gr.y → “gray”, “grey” |
^ | Matches start of a string | ^hello matches “hello world” but not “world hello” |
$ | Matches end of a string | world$ matches “hello world” |
* | Matches 0 or more occurrences | a* matches “”, “a”, “aaa” |
+ | Matches 1 or more occurrences | a+ matches “a”, “aaa” but not “” |
? | Matches 0 or 1 occurrences | colou?r matches “color” and “colour” |
{n} | Matches exactly n times | \d{3} matches “123” but not “12” |
{n,} | Matches at least n times | \d{2,} matches “12”, “123” |
{n,m} | Matches between n and m times | \d{2,4} matches “12”, “123”, “1234” |
[] | Matches a range of characters | [aeiou] matches vowels |
\d | Matches digits (0-9) | \d+ matches “123” |
\w | Matches letters, numbers, underscore | \w+ matches “abc123” |
\s | Matches whitespace | \s+ matches spaces, tabs |
` | ` | Acts as OR operator |
3.3 Using preg_match()
preg_match() checks if a pattern exists in a string and returns 1 (match) or 0 (no match).
Example: Validate Email
<?php
$email = “test@example.com”;
if (preg_match(“/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/”, $email)) {
echo “Valid Email!”;
} else {
echo “Invalid Email!”;
}
?>
3.4 Using preg_replace()
preg_replace() replaces text matching a pattern.
Example: Remove Special Characters
<?php
$text = “Hello! How’s it going?”;
$cleanText = preg_replace(“/[^a-zA-Z0-9\s]/”, “”, $text);
echo $cleanText; // Output: “Hello Hows it going”
?>
3.5 Using preg_match_all()
preg_match_all() finds all matches of a pattern in a string.
Example: Extract All Digits
<?php
$text = “My number is 12345 and my friend’s is 67890.”;
preg_match_all(“/\d+/”, $text, $matches);
print_r($matches[0]); // Output: Array ( [0] => 12345 [1] => 67890 )
?>
4. Real-World Applications of Regular Expressions
✅ Email Validation
if (preg_match(“/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/”, $email)) { … }
✅ Phone Number Validation
if (preg_match(“/^\+?\d{1,3}[-.\s]?\d{3}[-.\s]?\d{4}$/”, $phone)) { … }
✅ Extract Links from HTML
preg_match_all(‘/<a href=”(.*?)”>/’, $html, $matches);
✅ Password Strength Checking
if (preg_match(“/^(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,}$/”, $password)) { … }
5. Summary
Concept | Description |
String Manipulation | Use functions like strlen(), str_replace(), explode(), implode() |
RegEx Matching | Use preg_match(), preg_replace(), preg_match_all() |
RegEx Special Characters | `. ^ $ * + ? {n,m} [ ] \d \w \s |
RegEx Use Cases | Email validation, form validation, search |
6. Conclusion
📌 Strings are used for basic text operations, while regular expressions provide powerful pattern matching and validation. Combining both helps in data cleaning, validation, and extraction.