首页 > 解决方案 > PHP 根据数组检查 URL 参数

问题描述

我正在使用以下代码来回显 URL 的一部分,我的动态 URL 现在看起来像这样。

https://example.test/test.php?name=living-room

name但条件是,只有当URL 的一部分在我的数组中时,它才会回显。

$array = array('kitchen', 'bedroom', 'living room', 'dining room');
if (in_array($_GET['name'], $array))
{echo $_GET['name'];}  
else {header("HTTP/1.0 404 Not Found");}

我正在尝试做的是将-in URL 的name部分视为空格。

例如,living-room应该等于living room我的数组中的值,它应该回显我的数组中的值 ( living room) 而不是 ( living-room)。

  1. 因此,如果 URL 的值为living-room,我们检查数组,因为living room存在于数组中living room会得到回显。
  2. 与以前一样,如果 URL 的值为dining-room,因为dining room存在于我的数组中,dining room将得到回显。

我很难找到正确的逻辑。

标签: phparrays

解决方案


您可以在从 URL 参数回显字符串时进行字符串替换。你可以这样做:

header("Content-Type: text/plain");
$name = $_GET['name'];
$name = str_replace("-"," ",$name); // Replace - with space
    
$array = ['kitchen', 'bedroom', 'living room', 'dining room'];
    
if (in_array($name, $array, true)) {
    // Found
    echo $name, "\n"; 
} else {
    // Not found
    header("HTTP/1.0 404 Not Found");
}

推荐阅读