以下列出了php中的大部分字符串函数及正则表达式的规则,更多细节需要对照php手册-文本处理:
/**
* 字符串的格式化
* */
// 字符串的整理 trim() chop() 以及ltrim()、rtrim()
$name=" I'm not a loser ";
$name1=trim($name);
$name2=chop($name);
echo $name1."
";
echo $name2."
";
//使用html格式化 nl2br()
$name3=nl2br($name);
echo $name3."
";
//为打印输出格式化 print()、printf()、sprintf()
$total=45.2;
$total_shipping=12.5;
printf("total amount of order is %s.",$total);
echo"
";
printf("total amount of order is %.2f.",$total);
echo"
";
printf("total amount of order is %.2f (with shipping %.3f)",$total,$total_shipping);
echo"
";
printf("total amount of order is %2$.2f (with shipping %1$.2f)",$total_shipping,$total);
echo"
";
//改变字符串中的字母大小写 strtouper()、strtolower()、ucfirst()、ucwords()
echo strtoupper($name)."
";
echo ucwords($name)."
";
//格式化字符串以便存储:addslashes()、stripslashes()
$name4=addslashes(trim($name));
echo $name4."
";
$name5=stripslashes(trim($name));
echo $name5."
";
/**
* 字符串的连接和分割
* */
//字符串的分割 explode(),strtok(),substr()
$info="my name is jason, I'm from china,and you?";
$info_array=explode(',',$info);
for($i=0;$i
echo $info_array[$i]."
";
}
$token=strtok($info,',');
echo $token."
";
while($token !=""){
$token=strtok(",");
echo $token."
";
}
echo substr($info,0,7)."
";
//字符串的连接 implode()、join()
echo implode(",",$info_array)."
";
echo join(",",$info_array)."
";
/**
* 字符串的比较
* */
//字符串的排序 strcmp()、strcasecmp()、strnatcmp()
echo strcmp(2,12)."
";
echo strcmp(a,A)."
";
echo strcasecmp(a,A)."
";
echo strnatcmp(2,12)."
";
//测试字符串的长度 strlen()
echo strlen("hello")."
";
//在字符串中查找字符串:strstr()、strchr()、strrchr()、stristr()
$test="hi! jason are you ok?";
//echo strstr($test,'jason');
//查找子字符串的位置:strpos()、strrpos()
echo strops($test,"o");
//替换子字符串:str_replace()、substr_replace()
$feedback="fuck you! your product is so bad";
echo str_replace('fuck','%!**',$feedback);
/**
* 正则表达式
*/
//.at、#at、[a-z]at [^a-z]at、[[:alnum]]+、(very )*large、(very ){1,3}、^[a-z]$、com|edu|net
//验证email:^[a-zA-Z0-9_-.]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$
//用正则表达式查找子字符串:ereg()、eregi()
$email="bboyjoe05@163.com";
$regex="^[a-zA-Z0-9_-.]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$";
if(!eregi($regex,$email)){
echo "
This is not a valid email address
";//exit;
}
//用正则表达式替换子字符串:ereg_replace、eregi_replace
//施工正则表达式分割字符串:split()
$address="username@example.com";
$arr=split(".|@",$address);
while(list($key,$value)=each($arr)){
echo "
".$value;
}