1

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).

  1. So if the URL's value is living-room, we check the array and since living room exists in the array living room will get echoed.
  2. In the same way as before, if the URL's value is 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.

2
  • It's fine if you're eager to learn PHP, but could you please, on Stackoverflow, before creating new contributions research your topic in existing contributions first? Your previous question follows borderline a similar pattern. There is also the PHP documentation available for studying which has the bricks you can build the logic on. Commented Jul 19, 2021 at 21:18
  • StackOverflow is not a free coding service. You're expected to try to solve the problem first. Please update your question to show what you have already tried in a minimal reproducible example. For further information, please see How to Ask, and take the tour. Commented Jul 19, 2021 at 21:29

2 Answers 2

3

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");
}
Sign up to request clarification or add additional context in comments.

Comments

2

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.