1

I pray that my question isn't confusing. I have made a search engine where people can search the city and state like so "Atlanta, GA" What I want is no matter how they type it whether it's like Atlanta,GA or Atlanta GA or Atlanta, GA it will still find the results. Now I tried doing this with PHP STR and I don't know if this is right. Here is my code. Thanks.

 $userinput=$request->input('cityandstate');

 $stq=str_replace(",",", ", $userinput);  
2
  • Does your search engine require the city and state to be like <city> comma space <state>? Commented Sep 19, 2018 at 3:45
  • yes it does but sometimes you have people that don't that rule so I just want to be prepare for that Commented Sep 19, 2018 at 3:48

2 Answers 2

1

You can use preg_replace to get the user input into the exact form required by your search engine. preg_replace let's you allow for all sorts of inputs with multiple spaces and with or without commas:

$userinputs =array("Atlanta  GA", "Atlanta,GA", "Atlanta , GA", "Atlanta, GA ", " Atlanta   ,GA");
foreach ($userinputs as $userinput) {
   $stq = preg_replace('/^\s*(\w+)\s*,?\s*(\w+)\s*$/', '$1, $2', $userinput);
   echo "$stq\n";
}    

Output:

Atlanta, GA
Atlanta, GA
Atlanta, GA
Atlanta, GA
Atlanta, GA
Sign up to request clarification or add additional context in comments.

Comments

0

This will replace any comma in the string with nothing.

$stq = str_replace(",", "", $userinput);

See http://php.net/manual/en/function.str-replace.php

str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

This will not help you if a user inputs Atlanta - GA and you may be better served by using a preg_replace http://php.net/manual/en/function.preg-replace.php

6 Comments

Okay I will try that
I tried it and it worked, quick question can I also do something like this Miami, fl replaced with Miami,fl? I tried doing this $stq=str_replace(", ", ",",$userinputt);
its not working. I did $stq=str_replace(", ", ",", $userinputt); its not replacing Miami, fl with Miami,fl
It appears you have a spelling mistake? $userinputt has an extra t? This worked for me. $userinput = "Atlanta, GA"; $newString = str_replace(", ", ",", $userinput); echo $newString;
but $userinputt is what I named the variable
|

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.