字符串与正则表达式php,php的字符串操作与正则表达式

以下列出了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;

}

3707cfafeacd7ae58f0d20daa661a06f.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值