php - 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
)。
- 因此,如果 URL 的值为
living-room
,我们检查数组,因为living room
存在于数组中living room
会得到回显。 - 与以前一样,如果 URL 的值为
dining-room
,因为dining room
存在于我的数组中,dining room
将得到回显。
我很难找到正确的逻辑。
解决方案
您可以在从 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");
}
推荐阅读
- spark-ar-studio - 如何在 Spark AR 中指定 2D 对象(如矩形)的初始位置?
- excel - 仅计算当月的工作时间
- android - 再次:类'X'不是抽象的,不实现抽象成员公共抽象乐趣writeToParcel
- python - Pip install 不安装任何 .py 文件
- ruby-on-rails - Ruby 中带有复选框和多对多关系的嵌套表单
- java - 使用导航控制器从先前实例中检索数据
- mysql - 更改包含某些字符的表的所有列
- python-3.x - Leetcode Medium:旋转一个链表
- firebase - 我如何在颤振中获得 Firestore 集合和子集合
- php - 在 MySQL 视图中获取当前登录的 wordpress 用户 ID