----- 014-string.php -----
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 5 <title>一个PHP网页</title> 6 </head> 7 <body> 8 <pre> 9 <?php 10 echo "<h3>字符串比较</h3>"; 11 $str1 = "hello"; 12 $str2 = "HELLO"; 13 printf("%s比%s:%d\n", $str1, $str2, strcmp($str1, $str2)); 14 printf("%s比%s不区分大小写:%d\n", $str1, $str2, strcasecmp($str1, $str2)); 15 $str1 = "helWWW"; 16 $str2 = "HELQQQ"; 17 printf("%s比%s,前三个字符:%d\n", $str1, $str2, strncmp($str1, $str2, 3)); 18 printf("%s比%s,前三个字符,不区分大小写:%d\n", $str1, $str2, strncasecmp($str1, $str2, 3)); 19 ?> 20 <?php 21 echo "<h3>字符串替换</h3>"; 22 $str = "葫芦"; 23 $result = str_replace("葫芦", "葫芦娃", $str, $count); 24 printf("葫芦(葫芦->葫芦娃):%s。替换了%d次\n", $result, $count); 25 $result = substr_replace($str, "葫芦娃", 3, 3);//UTF-8 26 printf("葫芦(2+2->葫芦娃):%s。\n", $result); 27 ?> 28 <?php 29 echo "<h3>截取字符串</h3>"; 30 $str = "植物大战大僵尸"; 31 printf("植物大战大僵尸,从大开始:%s\n", strchr($str, "大")); 32 printf("植物大战大僵尸,从大开始,取左半部分:%s\n", strchr($str, "大", true)); 33 printf("植物大战大僵尸,大的位置:%d\n", strpos($str, "大", 0)); 34 printf("植物大战大僵尸,大的位置:从第三个字开始%d\n", strpos($str, "大", 9)); 35 printf("植物大战大僵尸,从右边的大开始:%s\n", strrchr($str, "大")); 36 printf("植物大战大僵尸,从第二个字符开始:%s\n", substr($str, 3)); 37 printf("植物大战大僵尸,大出现次数:%s\n", substr_count($str, "大")); 38 ?> 39 <?php 40 echo "<h3>分割字符串</h3>"; 41 $str = "植物 大战 僵尸"; 42 $s = strtok($str, " "); 43 while ($s) { 44 echo $s, "\n"; 45 $s = strtok(" "); 46 } 47 foreach(explode(" ", $str) as $temp){ 48 echo $temp, "\t"; 49 } 50 echo implode("+", array("植物", "大战", "僵尸")); 51 ?> 52 <?php 53 echo "<h3>大小写转换</h3>"; 54 echo strtolower("PHP"), "\n"; 55 echo strtoupper("java"), "\n"; 56 echo ucfirst("what you see is what you get"), "\n"; 57 echo ucwords("what you see is what you get"), "\n"; 58 foreach(count_chars("abbcccdddd", 1) as $key=>$value){ 59 echo $key, "=>", $value, "\n"; 60 } 61 ?> 62 <?php 63 echo "<h3>字符串填充</h3>"; 64 $arr = array("柯南", "海贼王", "火影忍者", "樱桃小丸子"); 65 foreach ($arr as $value) { 66 echo str_pad($value, 18, "—", STR_PAD_LEFT); 67 echo "\n"; 68 } 69 ?> 70 <?php 71 echo "<h3>字符串剔除</h3>"; 72 $str = "** 滴滴动力** "; 73 echo "待剔除字符串:|", $str, "|\n"; 74 echo "剔除空格|", trim($str), "|\n"; 75 echo "剔除星号|", trim($str, "*"), "|\n"; 76 echo "剔除星号空格|", trim($str, "* "), "|\n"; 77 echo "左剔除星号空格|", ltrim($str, "* "), "|\n"; 78 echo "右剔除星号空格|", rtrim($str, " *"), "|\n"; 79 ?> 80 </pre> 81 </body> 82 </html>
原文:http://www.cnblogs.com/baijifeilong/p/3750413.html