Write a program to implement the following functions:
a. How to determine whether a character exists in a string
echo strstr('abcdefgcd' , 'cd'); echo strpos('ab0defgcd' , 'cd');
Example:
<?php $str = 'abcdef'; $find = 'abc'; $pos = strpos($mystring, $findme); // 注意这里使用的是 ===不能使用== // 因为如果没有字符串 就返回false,如果这个字符串位于字符串的开始的地方,就会返回0为了区分0和false就必须使用等同操作符 === 或者 !== if ($pos === false) { echo "$find不在$str中"; } else { echo "$find在$str中"; } ?>
<?php $string = 'abcdef abcdef'; $find = strpos($string,'a',1); // $find = 7, 不是 0 ?>
b. How to determine a string How many times does a character appear in?
echo substr_count('abcdefgcd' , 'cd');
Example:
<?php $str = 'fdafdasfsfwrewonvxzf'; $count = Array(); $len = strlen($str); for($i=0; $i<$len; $i++) { $v = substr($str, $i, 1); $count[$v]++; } print_r($count); ?>
c. How to remove the last character of a string
echo substr('abcdefgcd' , 0 , -1);
Example:
$str = "1,2,3,4,5,6,"; $newstr = substr($str,0,strlen($str)-1); echo $newstr; //echo 1,2,3,4,5,6
The above is the detailed content of Write a program in PHP to implement the following functions. For more information, please follow other related articles on the PHP Chinese website!