Write a program in PHP to implement the following functions

不言
Release: 2023-03-28 16:38:01
Original
1877 people have browsed it

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');
Copy after login

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中";
}
?>
Copy after login
<?php
$string = &#39;abcdef abcdef&#39;;
$find = strpos($string,&#39;a&#39;,1); // $find = 7, 不是 0
?>
Copy after login

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

echo substr_count(&#39;abcdefgcd&#39;  , &#39;cd&#39;);
Copy after login

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);
?>
Copy after login

c. How to remove the last character of a string

echo substr(&#39;abcdefgcd&#39;  , 0 ,  -1);
Copy after login

Example:

$str = "1,2,3,4,5,6,"; 
$newstr = substr($str,0,strlen($str)-1); 
echo $newstr; 
//echo 1,2,3,4,5,6
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template