Regular expressions are powerful tools widely used in PHP for string matching and manipulation. This article systematically introduces the basic usage and practical examples of PHP regular expressions to help readers quickly grasp their core concepts.
The most commonly used function for regex matching in PHP is preg_match(). Here are the core regex syntax elements:
$email = "example@example.com";
if(preg_match("/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/", $email)){
echo "Valid Email Address!";
}else{
echo "Invalid Email Address!";
}
$phone = "13812345678";
if(preg_match("/^1[3456789]\d{9}$/", $phone)){
echo "Valid Phone Number!";
}else{
echo "Invalid Phone Number!";
}
$html = '<div><p>Hello, World!</p></div>';
preg_match("/<p>(.*?)<\/p>/", $html, $matches);
echo "Extracted Content: " . $matches[1];
$oldStr = "Hello, PHP!";
$newStr = preg_replace("/PHP/", "World", $oldStr);
echo "Replaced String: " . $newStr;
$str = "Hello, World!";
if(preg_match("/World/", $str)){
echo "The string contains 'World'!";
}else{
echo "The string does not contain 'World'!";
}
Beyond basic matching, regular expressions support capture groups and assertions that enable more complex matching logic. The following example shows how to extract sentences containing a specific keyword:
$text = "I love PHP. PHP is a powerful language. PHP is widely used.";
preg_match_all("/(.*?PHP.*?)./", $text, $matches);
foreach($matches[1] as $sentence){
echo $sentence . ".";
}
This article’s examples provide a thorough understanding of PHP regular expression syntax and practical skills, allowing you to apply them flexibly in everyday development tasks. Mastery of regex is a vital skill for efficient and high-quality coding. We hope this guide aids your learning journey, and encourage you to continue exploring and practicing based on your projects.