时间:2021-07-01 10:21:17 帮助过:9人阅读
Perl兼容的正则表达式
一、函数:
preg_match():指示模式是否与字符串匹配,一旦找到一个匹配返回1,否则返回0
preg_match_all():找到所有的匹配
preg_replace():实现查找和替换作用
二、简单的模式:
1. 字面量:是一个值,其书写方式与所解释的完全一样。例如,模式a将匹配字母a,ab将匹配ab等。
定界符:可以是除字母数字或反斜杠外的任何字符,必须使用相同的字符来标记模式的开始和结束。通常使用正斜杠(/)
元字符 :
量词:
常见的字符类别:
三、实践:
1.单一匹配——pcre.php
<htmllang="en"><head><metacharset="UTF-8"><title>Testing PCREtitle>head><body># Script 14.1- pcre.phpif($_SERVER['REQUEST_METHOD'] == 'POST')
{
$pattern = trim($_POST['pattern']);
$subject = trim($_POST['subject']);
echo"The result of checking
$pattern
aganist
$subject
is
";
if(preg_match($pattern, $subject))
{
echo'TRUE!';
}else{
echo'FALSE!';
}
}
?><formaction="pcre.php"method="post"><p>Regular Expression Pattern: <inputtype="text"name="pattern"value=""size="40">(include the delimiters)p><p>Test Subject: <inputtype="text"name="subject"value=""size="40" />p><inputtype="submit"name="submit"value="Test!">form>body>html>
——实现电子邮件验证:电子邮件开始于字母、数字或下划线,以及句点(.)或短划线。
2.所有匹配——matches.php
<htmllang="en"><head><metacharset="UTF-8"><title>Testing PCREtitle>head><body># Script 14.1- pcre.phpif($_SERVER['REQUEST_METHOD'] == 'POST')
{
$pattern = trim($_POST['pattern']);
$subject = trim($_POST['subject']);
echo"The result of checking
$pattern
aganist
$subject
is
";
if(preg_match_all($pattern, $subject, $matches))
{
echo'TRUE!';
echo''
.print_r($matches, 1).''
;
}else{
echo'FALSE!';
}
}
?><formaction="matches.php"method="post"><p>Regular Expression Pattern: <inputtype="text"name="pattern"value=""size="40">(include the delimiters)p><p>Test Subject: <textareaname="subject"rows="5"cols="40">if(isset($subject)) echo htmlentities($subject); ?>textarea>p><inputtype="submit"name="submit"value="Test!">form>body>html>
3.匹配和替换——replace.php
<htmllang="en"><head><metacharset="UTF-8"><title>Testing PCREtitle>head><body># Script 14.1- pcre.phpif($_SERVER['REQUEST_METHOD'] == 'POST')
{
$pattern = trim($_POST['pattern']);
$subject = trim($_POST['subject']);
$replace = trim($_POST['replace']);
echo$subject;
echo"The result of replacing
$pattern
with
$replace
in
$subject
"
;
if(preg_match($pattern, $subject))
{
echo preg_replace($pattern, $replace, $subject).'';
}else{
echo'The pattern was not found!';
}
}
?><formaction="replace.php"method="post"><p>Regular Expression Pattern: <inputtype="text"name="pattern"value=""size="40">(include the delimiters)p><p>Replacement: <inputtype="text"name="replace"value=""size="40">p><p>Test Subject: <textareaname="subject"rows="5"cols="40">if(isset($subject)) echo htmlentities($subject); ?>textarea>p><inputtype="submit"name="submit"value="Test!">form>body>html>
').addClass('pre-numbering').hide();
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i <= lines; i++) {
$numbering.append($('').text(i));
};
$numbering.fadeIn(1700);
});
});
以上就介绍了PHP学习练手(十六),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。