fefe
fefe

Reputation: 9055

compare string variables with php

I try to figure out how to solve the following issue

$str = 'asus company';
$brands = "asus|lenovo|dell";

Than I would like to compare the 2 string variables and retrieve the matching sub string. The desired output would be 'asus'.

I know that I can use strtr function from php but this one returns just a boolean. I need the string as well.

Upvotes: 1

Views: 204

Answers (4)

aleation
aleation

Reputation: 4844

This is What I would Do:

$str = 'asus company';
$brands = "asus|lenovo|dell";

//Finding every single word (separated by spaces or symbols) and putting them into $words array;
preg_match_all('/\b\w+\b/', $str, $words);

//Setting up the REGEX pattern;
$pattern = implode('|', $words[0]);
$pattern = "/$pattern/i";

//Converting brands to an array to search with
$array = explode('|', $brands);

//Searching 
$matches = preg_grep($pattern, $array);

You face several problems there: If the string has commas or other symbols, then we can't just use explode to separate, that's why I used a preg_match all to separate them and set up a pattern.

With preg_grep you will avoid upper/lower case problems.


You can also array_intersect($words, $array) there as @Znarkus responded, instead of setting up a pattern and preg_grep(), but make sure you strtolower() $brands and $str before converting to array, I'm not sure if array_intersect() is case sensitive.

Upvotes: 1

Ripa Saha
Ripa Saha

Reputation: 2540

you may use like below

$array1 = explode(" ",$str);
$array2 = explode("|",$brands);
$result = array_intersect($array1, $array2);
print_r($result);

Upvotes: 0

sybear
sybear

Reputation: 7784

preg_match will do the work for you. Just remember that your regular expression has to be correct, meaning that in your case simple | delimiter is enough.

$str = 'asus company'; 
$brands = "asus|lenovo|dell"; 

preg_match("/($brands)/", $str, $matches);

echo $matches[1] ;

$matches contains occurences of the keywords. $matches[0] has the full string and $matches[1] has the first occurence and so on.

Upvotes: 1

Markus Hedlund
Markus Hedlund

Reputation: 24254

Assuming $str is separated by a space and $brands by a pipe, this should work:

<?php

$str = 'asus company';
$brands = "asus|lenovo|dell";

$array_str = explode(' ', $str);
$array_brands = explode('|', $brands);

var_dump(
    array_intersect($array_str, $array_brands)
);

The output is

array(1) {
  [0]=>
  string(4) "asus"
}

Upvotes: 4

Related Questions