Tim
Tim

Reputation: 127

PHP - How to find a specific number in a string?

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?

Upvotes: 0

Views: 59

Answers (1)

Inceddy
Inceddy

Reputation: 760

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;
}

Upvotes: 4

Related Questions