21.7习题
21.7 习题
一、填空题
1.___________实际上就是负责对字符串做解析对比,从而分析出字符串的构成,以便进一步并对字符串做相关的处理。
2.___________是正则表达式最基本的元素,它们是一组描述字符串特征的字符。
3.本章介绍的两种正则表达式函数分别是___________和___________。
4.注册一个网站时,我们经常需要输入用户名。用户名是含有字母、下划线和数字的任意个组合,写出一个检测用户名是否合法的正则表达式:___________。
二、上机实践
1.分别在字符串“PHP is the web scripting language of choice”和“PHP is the website scripting language of choice”中查找是否含有单独的单词web,进行表达式匹配。
【提示】
$string=preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice.", $matches); //
匹配
f ($string==true){ //
判断匹配结果
print "A match was found.<br>"; //
输出“A match was found
”
print_r($matches); //
输出数组变量
echo "<br>"; //
换行
} else { //
没有匹配上的情况
print "A match was not found.<br>"; //
输出“A match was not found
”
print_r($matches); //
输出数组变量
echo "<br>"; //
换行
}
$string=preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.",$matches);
if ($string==true) { //
判断匹配结果
print "A match was found."; //
输出“A match was found
”
print_r($matches); //
输出数组变量
echo "<br>"; //
换行
} else { //
没有匹配上的情况
print "A match was not found.<br>"; //
输出“A match was not found
”
print_r($matches); //
输出数组变量
}
2.将字符串“The quick brown fox jumped over the lazy dog.”中的“quick”、“brown”、“fox”分别替换为“bear”、“black”、“slow”,然后将字符串逆序排列,再进行替换。
【提示】
$string = "The quick brown fox jumped over the lazy dog.<br>";
$patterns[0] = "/quick/";
$patterns[1] = "/brown/";
$patterns[2] = "/fox/";
$replacements[2] = "bear";
$replacements[1] = "black";
$replacements[0] = "slow";
print preg_replace($patterns, $replacements, $string);
ksort($replacements);
print preg_replace($patterns, $replacements, $string);
上一篇:21.6小结
下一篇:第五篇PHP应用实例与常见面试题
