0

I run a sneakers affiliate site and I am trying to match imported product names with existing sneaker models by a keyword. With the many formats around I have to use a number sometimes, and numbers don't get matched with the code I use. I tried all the different php str- functions but none of them seem to like both numbers and strings.

 $models = array(
    '106' => 'Vans 106 Vulcanized',
    'alomar' => 'Vans Alomar',
    'atwood' => 'Vans Atwood',
    'authentic' => 'Vans Authentic',
    // List goes on...
 );

 foreach ( $models as $model_keyword => $model_name ) {

     if ( stristr( $product_name, $model_keyword ) !== false ) {

         return $model_name;

     }

 }

As you can see I am checking the product name for each of the keywords and when it's found return the model name. Works for every string that contains letters or letters and numbers but not just numbers like the first item in my array.

Any ideas on how to do this properly?

1 Answer 1

4

Use strpos instead.

<?php

$models = array(
    '106' => 'Vans 106 Vulcanized',
    'alomar' => 'Vans Alomar',
    'atwood' => 'Vans Atwood',
    'authentic' => 'Vans Authentic'
    // List goes on...
);

foreach ($models as $key => $name) {
    if (strpos($name, (string)$key) !== false)
        return $name;
}
Sign up to request clarification or add additional context in comments.

9 Comments

Or stripos for being not casesensitive.
Also the same problem. From the docs: If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. The product names containing '106' are still ignored.
@Tim Yes you are right: Cast the $keyto a string before (string)$key. I edited the answer.
Should've thought of that. This is the solution, thanks
@Tim But better use stripos it's faster ;)
|

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.