![](/img/trans.png)
[英]a code that checks the current url, checks if it contains a certain string
[英]Statement that checks whether a URL contains a particular path?
是否有 if 語句允許我檢查 URL 是否包含特定路徑?
在我的特殊情況下(使用 wordpress),我正在嘗試檢查 URL 是否包含/store/ https://www.website.com.au/store/brand/所以在那條路徑之后可能有一些東西......
謝謝您的幫助!
如果您不想創建 function,這是我使用的更簡單的選項。
if( strpos( $_SERVER["REQUEST_URI"], "/store/" ) !== false ){ /* found */ }
使用strpos()
函數。 它基本上找到子字符串在給定字符串中首次出現的位置。 如果未找到子字符串,則返回false
:
// input url string
$url = 'https://www.website.com.au/store/brand/';
$path_to_check_for = '/store/';
// check if /store/ is the url string
if ( strpos($url, $path_to_check_for) !== false ) {
// Url contains the desired path string
// your remaining code to do something in case path string is there
} else {
// Url does not contain the desired path string
// your remaining code to do something in case path string is not there
}
我建議使用WordPress函數,例如is_singular,is_tax等。
function get_current_url()
{
$pageURL = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "۸۰") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$url = get_current_url();
if (strpos($url, '/store/') !== false) {
echo 'found';
}else{
echo 'not found';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.