hello all,

Im trying to dynamically insert text onto a page by inserting a value from a query string using php. This was simple enough when i wanted to insert the entire value, but im having trouble finding information on how to search the value for a word (from a list of words) and if it contains one to echo/print just that word, not the entire value.

So far i have the basic 'return the whole value' scripts.

<?php if($_GET['KEY'] == "")
{
    // no keyword entered
    echo "";
}
else
{
    echo $_GET['KEY']." Or Any City";
}
?>
</span>

The value of the key contains a location eg. washington, the value could just be one word(and the above code works if it is), but its more likely to contain more words eg. ?key=washington something somethingelse

I need to find a way of searching this value against a list of locations (eg. washington, new york, la, etc.. If the value of the key contains one of the locations in the list, then i need to insert just that location into the page, not the entire value.

Im not sure how this is best done, if anyone has any ideas or knows where i can find help, it'd be much appreciated.

Thanks, Rika

Dani AI

Generated

— the easy answers in this thread (array loop from , tokenizing/strpos from ) all work for simple, single-word matches. For reliable extraction when the query can contain extra words and many multi-word city names, a single regular-expression lookup built from your canonical city list is cleaner and more accurate.

Sort the city list by length (longest first), escape each name for regex, build an alternation pattern wrapped with word-boundaries, then run a case-insensitive match. Sorting longest-first avoids matching the short substring of a multi-word city (for example matching "York" before "New York"). Use preg_quote on the city names to avoid regex injection, and sanitize/trim the GET value before testing.

Example pattern-building approach:

<?php
$cities = ['New York','Los Angeles','Washington','St. Louis']; // from DB/file
$key = isset($_GET['key']) ? substr(strip_tags($_GET['key']), 0, 200) : '';

usort($cities, function($a,$b){ return strlen($b) - strlen($a); });
$escaped = array_map(function($c){ return preg_quote($c, '/'); }, $cities);
$pattern = '/\b(?:' . implode('|', $escaped) . ')\b/iu';

if (preg_match($pattern, $key, $m)) {
    echo $m[0]; // matched city
}
?>

Notes and gotchas:

  • Word boundaries with some punctuation (apostrophes, hyphens, accented letters) can be tricky; use Unicode flag u and, if needed, custom lookarounds instead of \b.
  • Always sanitize and length-limit user input. Do not build the regex from untrusted input without escaping.
  • If the city list is very large, consider a more efficient multi-pattern search (Aho-Corasick) or indexing to avoid huge alternations.
  • If exact matches fail but you still want to handle typos, fall back to fuzzy checks (levenshtein/similarity) on the candidate list.

Recommended Answers

All 3 Replies

Member Avatar for Member #46692

Put the key locations in an array and loop through the array?

Member Avatar for Member #46692

Maybe something?

<?php

$word_to_match = "New York";

$locations = array("Washington","New York","Brooklyn");

foreach ($locations as $c)
{
  if ( $c == $word_to_match)
  {
    echo "Word found : $c <br>";
  }
  else
    echo "Nope <br>";
}
?>

You might also want to look at the function array_push which is presumably more flexible.

Btw, the above is untested and straight from my head, it may or may not work :)

If the user input is ,for example "house Seattle job" and you wanna get the Seattle word, you can do this with explode http://www.php.net/manual/en/function.explode.php

php if($_GET['KEY'] == "")
{
    // no keyword entered
    echo "";
}
else
{
    $userCity=array();
    $userCity=explode(" ",$_GET['key']);

Now you must loop through the userCity array and compare with another array or with what you used to store the city names
Here you must have a convetion.All the citynames must be in lower/uppercase in order to get a good comparison . So you must do an additional operation before using the for : $userInputCity=strtolower($_GET) assuming that the names in cities array are also lowercase

foreach($userCity as $key1 => $inputcity)
{  
      foreach($cities as $key2 => $cityname)
      {
           if($inputcity == $cityname)
             echo 'found a city';
        }
}

If the input city name is composed of a single word , this would work fine , but if is something like New York , Los Angeles than in the for loop you must add :

elseif($key1 != 0 )
 {
   $twoWordCity=$userCity[$key1-1]." ".$userCity[$key1];
   if( $twoWordCity == $cityname )
        echo 'found a city';
}

Later edit :

After a second thought , it's much easier to just use the strpos() , like this :

$myCityNamesArray=('london','new york','sydney',......);

$cityInput=strtolower($_GET['key']);

foreach($myCityNamesArray as $cityName )
{
    if( strpos( $cityInput , $cityName ) !== false )
    {
        echo 'found it ';
        break;
     }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.