0

I have a search form where I get the word that user write to search.

<li id="search">
      <?php
          if(isset($_POST['search'])){
          $search = $_POST['s'];
          $search = handle($search);
          header('Location: '.BASE.'/search/'.$search);
     }
    ?>
    <form id="search" method="post" enctype="multipart/form-data">
       <input name="s" type="text" size="40" placeholder="Search..." />
       <button type="submit" name="search"></button>
    </form>
</li> 

And Im trying to use a function to change special chars, because I realize that if some user search for example for "%" he gets an "400 error".

So it seems important to use a function to handle this.

function handle($string) {
   $string = str_replace(' ', '-', $string); 
   $string = preg_replace('/[^A-Za-z0-9\-]/', ' ', $string); 
   return preg_replace('/-+/', '-', $string);
}

But with this function Im having one issue, if user search for "%", my function is replacing this char to "", and because of this Im having an error: strpos(): Empty needle in $searchPos = strpos($result['content'],$search);

But in handle function I have $string = preg_replace('/[^A-Za-z0-9\-]/', ' ', $string), to change special chars for a space and not for nothing "".

Do you see what Im doing wrong here?

UserX
  • 1,295
  • 7
  • 25
  • 39
  • 1
    Don't you want `$search = urlencode($_POST['s']);`? http://php.net/urlencode – DaveRandom Aug 14 '14 at 22:40
  • 1
    Lots of options here, can convert them to HTMLentities then search for &foo, filter_var, etc: http://stackoverflow.com/questions/657643/how-to-remove-html-special-chars – MrYellow Aug 14 '14 at 22:44
  • Thanks one more time DaveRandom. Your solution seems to work fine. But now when I search for "%", all the results I have in database appear. Do you know why this can be happening? – UserX Aug 14 '14 at 22:57

0 Answers0