PHP正则表达式允许最多1'.' 或字符串中的''字符和'.' 或''不能在字符串的开头或结尾。这种正则表达式可以用来匹配大多数常规字符串,包括纯文本、HTML和XML等。
以下是一些PHP正则表达式的常见应用:
<?php
$email = 'example@example.com';
if (preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $email)) {
echo 'Valid email address';
} else {
echo 'Invalid email address';
}
?>
<?php
$url = 'https://www.example.com/path/to/file.php?query=value';
preg_match('/https?:\/\/(www\.)?([a-zA-Z0-9]+(-?[a-zA-Z0-9])*\.)+[a-zA-Z]{2,6}/', $url, $matches);
echo $matches[0];
?>
<?php
$phone = '+1 (123) 456-7890';
if (preg_match('/^\+\d{1,3} \(\d{3}\) \d{3}-\d{4}$/', $phone)) {
echo 'Valid phone number';
} else {
echo 'Invalid phone number';
}
?>
<?php
$ip = '192.168.1.1';
if (preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $ip)) {
echo 'Valid IPv4 address';
} else {
echo 'Invalid IPv4 address';
}
?>
<?php
$html = '<p>This is an example <strong>bold</strong> text.</p>';
if (preg_match('/<(.*?)>/si', $html, $matches)) {
echo $matches[1];
} else {
echo 'No match found';
}
?>
<?php
$css = 'background-color: red; color: blue; font-size: 16px';
if (preg_match('/\s*([a-z-]+):[\s]*(.*?);/si', $css, $matches)) {
echo $matches[1] . ' : ' . $matches[2];
} else {
echo 'No match found';
}
?>
<?php
$json = '{"name": "John Doe", "age": 30, "city": "New York"}';
if (json_decode(''.$json.'', true)) {
echo 'Valid JSON string';
} else {
echo 'Invalid JSON string';
}
?>
<?php
$yaml = 'name: John Doe
age: 30
city: New York';
if (yaml_parse_file($yaml)) {
echo 'Valid YAML file';
} else {
echo 'Invalid YAML file';
}
?>
<?php
$xml = '<root><tag1>value1</tag1><tag2>value2</tag2></root>';
if (xml_parse_into_struct($xml, $xml_data)) {
foreach ($xml_data as $element => $value) {
echo "Element: {$element}: {$value}\n";
}
} else {
echo 'Invalid XML string';
}
?>
<?php
$json = '{"name": "John Doe", "age": 30, "city": "New York"}';
$data = json_decode($json, true);
if ($data) {
echo 'Name: ' . $data['name'] . '<br>';
echo 'Age
领取专属 10元无门槛券
手把手带您无忧上云