I'm using the following code to echo a part of a URL and my dynamic URL now looks like this.
https://example.test/test.php?name=living-room
But the condition is that, it will only echo if the name part of the URL is in my array.
$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");}
What I'm trying to do is treat the - in URL's name part as spaces.
For example, living-room should be equal to living room in my array and it should echo the value in my array (living room) instead of (living-room).
living-room, we check the array and since living room exists in the array living room will get echoed.dining-room, since dining room exists in my array, dining room will get echoed.I'm having a hard time finding the correct logic to this.
You can do a string replace while echoing the string from URL parameter. You can do something like this:
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");
}
You can use str_replace to replace "-" (U+002D HYPHEN-MINUS) with " " (U+0020 SPACE) in your string like so:
header("Content-Type: text/plain");
$array = ['kitchen', 'bedroom', 'living room', 'dining room'];
$needle = str_replace("-", " ", $_GET['name']);
if (in_array($needle, $array, true)) {
echo $needle, "\n";
} else {
header("HTTP/1.0 404 Not Found");
}