PHP5 学习:TXT部分


Learning PHP 5 By David Sklar Publisher : O’Reilly Pub Date : June 2004 ISBN : 0-596-00560-1 Pages : 368 Chapter:Text 1.校验字符

// $_POST[‘zipcode’] 来自表单提交的变量 // “zipcode” $zipcode = trim($_POST[‘zipcode’]); // $zipcode 得到$_POST[‘zipcode’]变量的值,并去掉变量前后带的空格. $zip_length = strlen($zipcode);//获得变量$zipcode的长度 // 提示 ZIP code 不是5个字符的长度 if ($zip_length != 5) { print “Please enter a ZIP code that is 5 characters long.”; }

比较简略的写法

if (strlen(trim($_POST[‘zipcode’])) != 5) { print “Please enter a ZIP code that is 5 characters long.”; }

2.比较字符串

if ($_POST[‘email’] == ‘president@whitehouse.gov’) { print “Welcome, Mr. President.”; }

注意:这里的president@whitehouse.GOV 不匹配 President@Whitehouse.Gov or president@whitehouse.gov.因为它使用的是 == . 忽略大小写的比较方法.

if (strcasecmp($_POST[‘email’], ‘president@whitehouse.gov’) == 0) { print “Welcome back, Mr. President.”; }

3.字符格式化-货币格式

$price = 5; $tax = 0.075; printf(‘The dish costs $%.2f’, $price * (1 + $tax));

显示为: The dish costs $5.38 4.字符格式化-填充零

$zip = ‘6520’; $month = 2; $day = 6; $year = 2007; printf(“ZIP is %05d and the date is %02d/%02d/%d”, $zip, $month, $day, $year);

显示为: ZIP is 06520 and the date is 02/06/2007 5.字符格式化-显示符号位

$min = -40; $max = 40; printf(“The computer can operate between %+d and %+d degrees Celsius.”, $min, $max);

显示为: The computer can operate between -40 and +40 degrees Celsius. 6.改变大小写

print strtolower(‘Beef, CHICKEN, Pork, duCK’); print strtoupper(‘Beef, CHICKEN, Pork, duCK’);

显示为: beef, chicken, pork, duck BEEF, CHICKEN, PORK, DUCK 7.美化姓名(首字符大写)

print ucwords(strtolower(‘JOHN FRANKENHEIMER’));

显示为: John Frankenheimer 8.截取字符

// 截取 $_POST[‘comments’] 的前30个字符. print substr($_POST[‘comments’], 0, 30); // 加入省略号. print ‘…’;

如果变量$_POST[‘comments’] 的值为: The Fresh Fish with Rice Noodle was delicious, but I didn’t like the Beef Tripe. 将显示为: The Fresh Fish with Rice Noodl… 9.反向截取字符

print ‘Card: XX’; print substr($_POST[‘card’],-4,4);

如果变量$_POST[‘card’]的值为: 4000-1234-5678-9101 将显示为: Card: XX9101 10.字符替换

print str_replace(‘{class}’,$my_class, ‘Fried Bean Curd Oil-Soaked Fish’);

如果变量$my_class 的值为: lunch, 将显示为:

Fried Bean Curd Oil-Soaked Fish

常用作简单的模版处理.

comments powered by Disqus