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
在復雜模式匹配中的應用。正則表達式可以幫助你處理各種字符串操作,從而提高代碼的可讀性和可維護性。