首頁  >  文章  >  後端開發  >  如何在 PHP 中尋找字串中的字串?

如何在 PHP 中尋找字串中的字串?

Patricia Arquette
Patricia Arquette原創
2024-10-26 20:34:29316瀏覽

 How Can You Find Strings Within Strings in PHP?

在字串中找出單字:揭開PHP 的秘密

在程式設計領域,辨識較大字串中是否存在特定單字可以是一項常見任務。 PHP 是一種廣泛使用的腳本語言,提供了多種函數來滿足這種需求。

strpos() 及其不區分大小寫的對應項:stripos()

strpos() 函數是定位字串中子字串位置的簡單而有效的選擇。然而,其區分大小寫的特性可能會限制其在某些情況下的用處。為了適應不區分大小寫的搜索,PHP 提供了 stripos() 函數作為可行的替代方案。

<code class="php">$needle = "to";
$haystack = "I go to school";

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

strstr() 和stristr():搜尋與擷取

strstr() 與stristr() 函式將子字串偵測與擷取相符後的字串字串部分的功能結合起來。在區分大小寫方面,它們的操作與 strpos() 和 stripos() 類似。

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

preg_match():釋放正規表示式

適用於需要高階模式的場景匹配,preg_match() 成為一個強大的工具。 preg_match() 支援的正規表示式允許靈活且複雜的搜索,而不僅僅是簡單的字串比較。

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

match_my_string():封裝功能

到簡化單字搜尋功能的實現,可以建立自訂函數:

<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(): A PHP 8.0 Delight

PHP 8.0.0 引入了str_contains ,用於檢查一個字串是否包含另一個字串的專用函數。它提供了簡潔直觀的語法:
<code class="php">if (str_contains($haystack, $needle)) {
    echo "Found";
}</code>

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

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