strcmp,strncmp,strstr,strpos

| |
[{langcopy8} February 4, 2007 04:28 | by Xiao4 ]
strcmp:
区分大小写的字符串比较.
int strcasecmp ( string str1, string str2 )

如果str1小于str2则返回<0; str1大于str2时返回>0, 两个字符串相等时返回0.
eg:
引用

$var1 = "Hello";
$var2 = "Hello";
if (strcasecmp($var1, $var2) == 0) {
   echo '$var1和$var2在区分大小写的比较下相等';
}
?>


strcasecmp用法一致,但不区分大小写.



strncmp

和strcmp的区别在于,可以限制他只比较前面的n个字符.
int strncmp ( string str1, string str2, int len )




strstr

string strstr ( string haystack, string needle )

手册上是这样写的strstr -- Find first occurrence of a string .找到第一次出现的位置.区分大小写
但是从手册中给出的例子和注意事项看,他被用来提取出string needle后边的字符串

eg:
引用

$email = 'user@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
?>


不想区分大小写就用stristr,
只想确定string needle是否出现在haystack中或者只要提供出现位置时,使用strpos更省资源.




strpos

Find position of first occurrence of a string
返回目标字符在字符串中第一次出现的位置.如果找不到则返回布尔值false.区分大小写
注意:判断是否出现时应使用"===",因为该函数可能返回"0"即第一个字符就是要找的.

eq:
引用

$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
   echo "The string '$findme' was not found in the string '$mystring'";
} else {
   echo "The string '$findme' was found in the string '$mystring'";
   echo " and exists at position $pos";
}

// We can search for the character, 忽略 offset 位置前的字符串
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>



offset:指出开始搜索的位置,不论offset是几,返回的位置都是从字符串开头算起的.
不想区分大小写用stripos
找最后一次出现位置用strrpos




学习笔记 | 评论(5) | 引用(0) | 阅读(3863)
VV
March 16, 2007 19:24
天啊……英语都不明白了……再加上火星文字……我更瞢了……要做什么找电脑老师就好了嘛……真是……干嘛要学呢……望天——纳闷中……
默戚
February 7, 2007 13:35
shuai完全不懂的说
leo
February 4, 2007 22:58
第一万零一次的说
C#是微软搞的
微软搞的东西大家都知道容易入手
但对打基础没什么好处
Rwing Homepage
February 4, 2007 13:51
PHP的这些函数太屯了....远不及c#....
Xiao4 回复于 February 4, 2007 19:09
做c#永远都是拼积木.
February 4, 2007 12:56
天书fear
Xiao4 回复于 February 4, 2007 19:33
这个嘛~你又不是学这个的
分页: 1/1 第一页 1 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]