首頁  >  文章  >  後端開發  >  如何在 PHP 中檢查字串中是否存在單字?

如何在 PHP 中檢查字串中是否存在單字?

Patricia Arquette
Patricia Arquette原創
2024-10-27 11:54:02749瀏覽

How to Check If a Word Exists in a String in PHP?

如何使用PHP 確定字串中單字的存在

您正在尋找一個PHP 函數來驗證特定單字是否存在在一個更大的字串中。考慮以下偽代碼:

text = "I go to school"
word = "to"
if (word.exist(text)) {
    return true
else {
    return false
}

為了滿足此要求,PHP 提供了多種滿足不同場景的函數。

使用strpos()

對於只需要確定單字是否存在的簡單實例,strpos() 提供了一個簡單的方法:

<code class="php">$needle = "to";  // The word you're searching for
$haystack = "I go to school";  // The string to be searched

if (strpos($haystack, $needle) !== false) {
    echo "Found!";
}</code>

使用strstr()

如果您需要根據結果執行進一步的操作,strstr()提供了更大的靈活性:

<code class="php">if (strstr($haystack, $needle)) {
    echo "Found!";
}</code>

使用preg_match()

對於涉及正規表示式的複雜模式,preg_match() 適合:

<code class="php">if (preg_match("/to/", $haystack)) {
    echo "Found!";
}</code>

定義自訂函數

來打包這些將函數轉換為具有Needle 和haystack 預設值的自訂函數:

<code class="php">function match_my_string($needle = 'to', $haystack = 'I go to school') {
  if (strpos($haystack, $needle) !== false) return true;
  else return false;
}</code>

使用str_contains()(PHP 8.0.0 及更高版本)

PHP 8.0.0引入了str_contains():

<code class="php">if (str_contains($haystack, $needle)) {
    echo "Found";
}</code>

以上是如何在 PHP 中檢查字串中是否存在單字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn