1

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.

4

4 回答 4

4

假设$str由空格和$brands管道分隔,这应该有效:

<?php

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

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

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

输出是

array(1) {
  [0]=>
  string(4) "asus"
}
于 2013-09-17T10:15:53.853 回答
1

preg_match将为您完成工作。请记住,您的正则表达式必须是正确的,这意味着在您的情况下,简单的|分隔符就足够了。

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

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

echo $matches[1] ;

$matches包含关键字的出现。$matches[0]有完整的字符串并且$matches[1]第一次出现等等。

于 2013-09-17T10:10:03.170 回答
1

这就是我要做的:

$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);

您在那里面临几个问题:如果字符串有逗号或其他符号,那么我们不能只使用explode 来分隔,这就是我使用preg_match all 来分隔它们并设置模式的原因。

使用 preg_grep 您将避免大写/小写问题。


你也可以array_intersect($words, $array)在那里@Znarkus回应,而不是设置模式和preg_grep(),但确保你strtolower() $brands$str转换为数组之前,我不确定array_intersect()是否区分大小写。

于 2013-09-17T10:32:33.967 回答
0

你可以像下面这样使用

$array1 = explode(" ",$str);
$array2 = explode("|",$brands);
$result = array_intersect($array1, $array2);
print_r($result);
于 2013-09-17T10:17:51.423 回答