PHP 函数:strcmp,strncmp,strstr,strpos

strcmp,strncmp,strstr,strpos

strcmp:

区分大小写的字符串比较.
int strcasecmp ( string str1, string str2 )

如果str1小于str2则返回0, 两个字符串相等时返回0.
eg:

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

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