字串函數庫-搜尋類型_PHP

來源:互聯網
上載者:User
關鍵字 類型 搜尋 函數 字串 the string needl
相容:(PHP 3, PHP 4, PHP 5)
strpos -- Find position of first occurrence of a string
尋找字元在字串第一次出現的位置
文法:int strpos ( string haystack, mixed needle [, int offset] )
傳回值:整數
函數種類: 資料處理

內容說明:
英文:
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.
If needle is not found, strpos() will return boolean FALSE.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the beginning of haystack.

中文:
傳回參數 needle在字串 haystack中第一次出現的位置,以數字表示。不像strrpos( ),此函式可以取參數 needle全部的字串,而且會使用全部的字串。如果找不到參數 needle,則傳回 false。

如果參數 needle不是字串時,它會轉換成整數並且按照字元的順序值來使用。
參數 offset允許你去指定在 haystack中從那一個字元開始搜尋,傳回的位置依然是相對於 haystack的起點。

*值得注意的是 needle 只能是一個字元,中文字等就不適合了。

例子講解:

$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, ignoring anything before the offset

$newstring = 'abcdef abcdef';

$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0

?>

strpos()與substr_count()對比:

$mystring = "Hello Chris\";

if (substr_count($mystring, \"Hello\") == 0)

echo \"no\";

// same as:

if (strpos($mystring, \"Hello\") === false)

echo \"no\";

?>


對比下面兩個代碼注意數字情況下,容易出現的錯誤,數字整數情況下不能看成字串。

$val1=123;

$val2="123,456,789\";

if (strpos($val2, $val1)!==false) echo \"matched\";

else echo \"not matched\";

?>

結果為: not matched


$val1=(string)123;

$val2="123,456,789\";

if (strpos($val2, $val1)!==false) echo \"matched\";

else echo \"not matched\";

?>

結果為:not matched
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.