如何使用 PHP 檢查 URL 是否包含特定字串


什麼是 PHP?

PHP(超文字預處理器)是一種流行的指令碼語言,專為 Web 開發而設計。它廣泛用於建立動態和互動式的網頁。PHP 程式碼可以直接嵌入到 HTML 中,允許開發人員無縫地混合 PHP 和 HTML。PHP 可以連線到資料庫、處理表單資料、生成動態內容、處理檔案上傳、與伺服器互動以及執行各種伺服器端任務。它支援各種 Web 開發框架,例如 Laravel、Symfony 和 CodeIgniter,這些框架為構建 Web 應用程式提供了額外的工具和功能。PHP 是一種開源語言,擁有龐大的社群、豐富的文件以及豐富的庫和擴充套件生態系統。

如何使用 PHP 檢查 URL 是否包含特定字串

使用 strpos() 函式

PHP 中的 strpos() 函式用於查詢子字串在字串中首次出現的起始位置。如果子字串存在,則函式返回子字串的起始索引;否則,如果在字串(URL)中未找到子字串,則返回 False。

語法

int strpos( $String, $Substring )

$字串:此引數儲存執行搜尋的文字。

$子字串:此引數儲存要搜尋的模式或子字串。

示例

<?php
$url = "https://tutorialspoint.tw/php/";
// Check if the URL contains the string "example"
if (strpos($url, "tutor") !== false) {
   echo "The URL contains the string 'tutor'.";
} else {
   echo "The URL does not contain the string 'tutor'.";
}
// Another search substring
$key = 'hyderabad';
if (strpos($url, $key) == false) {
   echo $key . ' does not exists in the URL.';
}
else {
   echo $key . ' exists in the URL.';
}
?>

輸出

The URL contains the string 'tutor'.hyderabad does not exists in the URL.

使用 preg_match() 函式

PHP 中的 preg_match() 函式用於使用正則表示式進行模式匹配。它允許您檢查字串中是否存在某個模式。

語法

preg_match( $pattern, $subject )

引數

$模式:它是作為字串的搜尋正則表示式模式。

$主題:它是搜尋正則表示式模式的文字字串。

示例

<?php
// PHP program to find exach match substring
// Given a URL
$url = 'https://www.google.co.in/';
// Here '\b' represents the block
// This pattern search gfg as whole words
$pattern = '/\bgoogle\b/';
if (preg_match($pattern, $url) == false) {
	echo 'google does not exist in the URL. <br>';
} else {
	echo 'google exist in the URL .<br>';
}
// Given another URL
$url2 = 'https://www.google.co.in/';
// This pattern search function as whole words
$pattern = '/\bchrome\b/';
if (preg_match($pattern, $url2) == false) {
	echo 'chrome does not exist in the URL.';
} else {
	'chrome exist in the URL.';
}
?>

輸出

google exist in the URL.
chrome does not exist in the URL.

結論

總之,要檢查 PHP 中的 URL 是否包含特定字串,您可以使用 strpos() 或 preg_match() 函式。strpos() 函式在字串中搜索子字串,並返回其首次出現的起始位置,如果未找到則返回 false。它適用於簡單的字串匹配。例如,strpos($url, $substring) 可用於檢查 URL 是否包含特定字串。

另一方面,preg_match() 允許使用正則表示式進行模式匹配。它在字串中搜索模式,並返回匹配次數或在未找到匹配項時返回 false。正則表示式提供了更多靈活性和高階模式匹配功能。例如,preg_match("/pattern/", $url) 可用於檢查 URL 是否包含特定模式。這兩個函式都可用於 URL 匹配,但 preg_match() 提供了更強大的模式匹配功能,而 strpos() 對於基本字串匹配來說更簡單且更快。

更新於: 2023-07-31

4K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.