preg_match
是 PHP 中一个非常强大的正则表达式函数,它可以用于在字符串中搜索与正则表达式模式匹配的子串
$email = "example@example.com";
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
if (preg_match($pattern, $email)) {
echo "Email is valid";
} else {
echo "Email is invalid";
}
$phone = "123-456-7890";
$pattern = "/^\d{3}-\d{3}-\d{4}$/";
if (preg_match($pattern, $phone)) {
echo "Phone number is valid";
} else {
echo "Phone number is invalid";
}
$url = "https://www.example.com";
$pattern = "/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/";
if (preg_match($pattern, $url)) {
echo "URL is valid";
} else {
echo "URL is invalid";
}
$csv = "name,age,email\nJohn,30,john@example.com\nJane,28,jane@example.com";
$pattern = "/^(.*?)\n/";
if (preg_match_all($pattern, $csv, $matches)) {
foreach ($matches[1] as $row) {
$data = explode(",", $row);
echo "Name: " . $data[0] . ", Age: " . $data[1] . ", Email: " . $data[2] . "\n";
}
}
$text = "The price of this item is $10.";
$pattern = "/\$(.*?)\$/";
$replacement = "50";
$new_text = preg_replace($pattern, $replacement, $text);
echo $new_text; // Output: The price of this item is 50.
这些示例展示了 preg_match
在复杂模式匹配中的应用。正则表达式可以帮助你处理各种字符串操作,从而提高代码的可读性和可维护性。