首页 > 代码库 > classic example1

classic example1

 

  1    2   3 <?php  4 //1.连接一个heredoc定义的字符串  5 $html = <<<END  6 <div class = "divClass">  7 <ul class = "ulClass">  8 <li>  9 END 10 ."the list item"."</li></div>"; 11  12 echo $html; 13  14   15  16 结果:   the list item 17  18   19  20 //2.用strpos()来查找字符串,strpos必须用===或者!==,因为如果找到字符串,会返回开始处位置,值为0. 21 $email = "cccccc#cc.cc"; 22 if(strpos($email,‘@‘) === false){ 23 echo ‘there was no @ in the e-mail address!‘; 24 } 25  26 结果: there was no @ in the e-mail address! 27  28   29  30 //3.用substr()来提取一个子字符串 31 echo "<br/>"; 32 $string = ‘watch out for that tree‘; 33 $start = -17; 34 $length = 5; 35 $substring = substr($string,$start,$length); 36 echo $substring; 37  38 结果:out f 39  40   41  42 //4.用substr_replace()替换自字符串 43 //把从位置$start开始到$sold_string结尾处的所有字符 44 //替换成$new_substing 45 //$new_string = substr_replace($old_string,$new_substring,$statr); 46 echo "<br/>"; 47 echo substr_replace(‘my pet is a blue dog.‘,‘fish‘,‘12‘); 48  49 //把从$start位置开始的$length个字符替换成$new_substring 50 //$new_srting = substr_replace($old_string,$new_substring,$start,$length); 51 echo "<br/>"; 52 echo substr_replace(‘my pet is a blue dog.‘,‘green‘,‘12‘,4); 53  54 结果:  my pet is a fish 55  56 my pet is a green dog. 57  58   59  60 //5.处理字符串中每一个字节 61  62 echo "<br/>"; 63 $string = "this weekend,I‘m going shoping for a pet chicken"; 64 $vowels = 0; 65 for ($i = 0,$j = strlen($string);$i < $j; $i++){ 66 if(strstr(‘aeiouAEIOU‘,$string[$i])){ 67 $vowels++; 68 } 69 } 70 echo $vowels; 71  72 结果: 14 73  74   75  76 //6."Look and say"序列 77 echo "<br/>"; 78 function lookandsay($s){ 79 //将保存返回值的变量初始化为空字符串 80 $r = ‘‘; 81 //$m用于保存我们要查找的字符 82 //同时将其初始化为字符串中的第一个字符串 83 $m = $s[0]; 84  85 //$n用于保存我们找到的$m的数目,将其初始化为1 86 $n = 1; 87 for($i = 1;$j = strlen($s),$i < $j;$i++){ 88 //如果这个字符与上一个字符相同 89 if($s[$i] == $m){ 90 //这个字符的数目加1 91 $n++; 92 }else{ 93 //否则,把数目和这个字符追加到返回值 94 $r .=$n.$m; 95 //把要找的字符串设置为当前的字符 96 $m = $s[$i]; 97 //并把数目重置为1 98 $n = 1; 99 }100 }101 //返回构建好的字符串以及最终的数目和字符102 return $r.$n.$m;103 }104 for($i = 0,$s = 1;$i < 10; $i++){105 $s = lookandsay($s);106 echo "$s <br/>\n";107 }108 109 结果:110 111 1 112 11 113 21 114 1211 115 111221 116 312211 117 13112221 118 1113213211 119 31131211131221 120 13211311123113112211 121 122 //7.按字反转字符串123 echo "<br/>";124 $s = "Once upon a time there was a turtle.";125 $words = explode(‘ ‘,$s);126 $words = array_reverse($words);127 $s = implode(‘ ‘,$words);128 echo $s;129 130 结果: turtle. a was there time a upon Once131 132  133 134 //8.简化后按字翻转字符串的代码135 echo "<br/>";136 $z = "this is a dog.";137 $reversed_s = implode(‘ ‘,array_reverse(explode(‘ ‘,$z)));138 echo $reversed_s;139 140  141 142 结果: dog. a is this143 144 ?>

 

classic example1