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)),
    );
3
  • 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. Commented Mar 11, 2014 at 2: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. Commented Mar 11, 2014 at 3:58
  • possible duplicate of How can I check if a word is contained in another string using PHP? Commented Mar 11, 2014 at 11:47

2 Answers 2

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

1 Comment

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

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

https://www.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';
}

1 Comment

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

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.