返回
needle
在 haystack
中首次出現的數字位置。
同時注意字符串位置是從0開始,而不是從1開始的(沒有提供offset時)。
-
offset
如果提供了此參數,搜索會從字符串該字符數的起始位置開始統計
如果沒找到 needle,將返回
FALSE(因此應該用===來測試返回的值)
。
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// 注意這里使用的是 ===。簡單的 == 不能像我們期待的那樣工作,
// 因為 'a' 是第 0 位置上的(第一個)字符。
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";
}
?>
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// 注意這里使用的是 ===。簡單的 == 不能像我們期待的那樣工作,
// 因為 'a' 是第 0 位置上的(第一個)字符。
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";
}
?>
<?php
// 忽視位置偏移量之前的字符進行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>
// 忽視位置偏移量之前的字符進行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>
- stripos() - 查找字符串首次出現的位置(不區分大小寫)
- strrpos() - 計算指定字符串在目標字符串中最后一次出現的位置
- strripos() - 計算指定字符串在目標字符串中最后一次出現的位置(不區分大小寫)
返回 haystack
字符串從 needle
第一次出現的位置開始到 haystack
結尾的字符串。
-
before_needle
若為 TRUE
,strstr() 將返回 needle
在 haystack
中的位置之前的部分。
Note:
該函數區分大小寫。如果想要不區分大小寫,請使用 stristr()。
Note:
<?php
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // 打印 @example.com
$user = strstr($email, '@', true); // 從 PHP 5.3.0 起
echo $user; // 打印 name
?>
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // 打印 @example.com
$user = strstr($email, '@', true); // 從 PHP 5.3.0 起
echo $user; // 打印 name
?>
- stristr() - strstr 函數的忽略大小寫版本
string
substr ( string
$string
, int
$start
[, int
$length
] )
返回字符串 string
由 start
和 length
參數指定的子字符串。
-
string
輸入字符串。
-
start
如果 start
是非負數,返回的字符串將從 string
的 start
位置開始,從 0 開始計算。例如,在字符串 “abcdef” 中,在位置 0 的字符是 “a”,位置 2 的字符串是 “c” 等等。
如果 start
是負數,返回的字符串將從 string
結尾處向前數第 start
個字符開始。
如果
string
的長度小於或等於
start
,將返回
FALSE
。
$rest = substr("abcdef", -1); // 返回 "f"
$rest = substr("abcdef", 0, -1); // 返回 "abcde"
$rest = substr("abcdef", 2, -1); // 返回 "cde"
$rest = substr("abcdef", 4, -4); // 返回 ""
$rest = substr("abcdef", -3, -1); // 返回 "de"
$rest = substr("abcdef", 2, -1); // 返回 "cde"
$rest = substr("abcdef", 4, -4); // 返回 ""
$rest = substr("abcdef", -3, -1); // 返回 "de"
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
// 訪問字符串中的單個字符
// 也可以使用中括號
$string = 'abcdef';
echo $string[0]; // a
echo $string[3]; // d
echo $string[strlen($string)-1]; // f
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
// 訪問字符串中的單個字符
// 也可以使用中括號
$string = 'abcdef';
echo $string[0]; // a
echo $string[3]; // d
echo $string[strlen($string)-1]; // f