0

I have edited my original question because I think made it more complicated than what I need.

Here is what I need to add:

  1. Check if the input for $query has the word hockey in it
  2. if not append hockey to the string
  3. return $query

Here is the portion of the php code that I need to adjust:

public function search($query, $size = 10, $page = 0, $location = '', $miles = 5, $sort = 'rd') {
    $params = array(
      'q' => rawurlencode(trim($query)),
      'sb' => $sort,
      'ws' => $size,
      'pn' => (intval($page) < 1 ? 0 : intval($page)),
    );
Torads
  • 69
  • 1
  • 10
  • just hard code hockey into the query. If it should always be included, it doesn't matter if someone selects it or not. Then you just append the other items they choose to the query. – Mattt Mar 11 '14 at 02:46
  • I may have not worded my question correctly as I understand what needs to be done, just looking for a few clever ways to make it happen. I have tried using a preg match looking for the word hockey and then adding it if not but I am getting something wrong in my syntax as it breaks. I'm now back to where I started. I will give it another go and submit the code here that I'm screwing up. – Torads Mar 11 '14 at 03:58
  • possible duplicate of [How can I check if a word is contained in another string using PHP?](http://stackoverflow.com/questions/1019169/how-can-i-check-if-a-word-is-contained-in-another-string-using-php) – Kami Mar 11 '14 at 11:47

2 Answers2

1

You don't need a regex for this; strpos will be faster anyway. Note the triple === sign. (manual)

public function search($query, $size = 10, $page = 0, $location = '', $miles = 5, $sort = 'rd') {

    if( strpos( $query, 'hockey' ) === false ) {
        $query .= ' hockey';
    }

    $params = array(
      'q' => rawurlencode(trim($query)),
      'sb' => $sort,
      'ws' => $size,
      'pn' => (intval($page) < 1 ? 0 : intval($page)),
    );
djb
  • 5,591
  • 5
  • 41
  • 47
  • Thanks djb, what I was trying was much more complicated than what you have provided me and best of all it's working good. Much appreciated. – Torads Mar 11 '14 at 12:32
0

Use strpos to find the first ocurrence of hockey in the queried string

http://es1.php.net/manual/en/function.strpos.php

The function strpos returns false if the substring (in this case, hockey is not found).

So you can do something like:

if !strpos($query, 'hockey') {
    $query = $query . ' hockey';
}
versvs
  • 643
  • 2
  • 12
  • 30
  • 2
    That will fail for strpos('hockey', 'hockey') as it will return 0 - see the note in the php manual on the return value of strpos – djb Mar 11 '14 at 11:51