Home >Backend Development >PHP Tutorial >Write a program in PHP to implement the following functions

Write a program in PHP to implement the following functions

不言
不言Original
2018-05-31 13:31:071919browse

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 = &#39;abcdef&#39;;
$find   = &#39;abc&#39;;
$pos = strpos($mystring, $findme);

// 注意这里使用的是 ===不能使用==
// 因为如果没有字符串 就返回false,如果这个字符串位于字符串的开始的地方,就会返回0为了区分0和false就必须使用等同操作符 === 或者 !==
if ($pos === false) {
    echo "$find不在$str中";
} else {
    echo "$find在$str中";
}
?>
<?php
$string = &#39;abcdef abcdef&#39;;
$find = strpos($string,&#39;a&#39;,1); // $find = 7, 不是 0
?>

b. How to determine a string How many times does a character appear in?

echo substr_count(&#39;abcdefgcd&#39;  , &#39;cd&#39;);

Example:

<?php
$str = &#39;fdafdasfsfwrewonvxzf&#39;;
$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(&#39;abcdefgcd&#39;  , 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn