我正在尝试使用以下代码来检查当前URL是否在数组中。
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (strpos($url, $reactfulPages) == true) {
echo "URL is inside list";
}
我认为我设置数组的方式不正确,因为以下代码(检查一个 URL)工作正常。
if (strpos($url,'url-one') == true) { // Check if URL contains "landing-page"
}
谁能帮我?
数组
很好,要检查的函数不是正确的方法。strpos()
函数用于检查字符串位置。
检查数组中是否有内容的正确方法可以使用in_array()
函数。
<?php
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if(in_array($url, $reactfulPages)) {
echo "The URL is in the array!";
// Continue
}else{
echo "The URL doesn't exists in the array.";
}
?>
我希望这对你有用。
该函数strpos()
在字符串中查找子字符串,如果找到子字符串,则返回子字符串的位置。这就是为什么你的最后一个例子有效。
如果要检查数组中是否存在某些内容,则应使用 in_array()
函数,如下所示:
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (in_array($url, $reactfulPages) == true) {
echo "URL is inside list";
}
但是,由于您正在比较 URL,我假设您要检查 URL 是否包含数组中的一个字符串,不一定将它们作为一个整体匹配。在这种情况下,您需要编写自己的函数,该函数可能如下所示:
function contains_any($string, $substrings) {
foreach ($substrings as $match) {
if (strpos($string, $match) >= 0) {
// A match has been found, return true
return true;
}
}
// No match has been found, return false
return false;
}
然后,您可以将此函数应用于您的示例:
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (contains_any($url, $reactfulPages)) {
echo "URL is inside list";
}
希望这有帮助。