比较字符串变量与PHP

时间:2013-09-17 10:06:01

标签: php string compare

我试图弄清楚如何解决以下问题

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

比我想比较2个字符串变量并检索匹配的子字符串。期望的输出为'asus'

我知道我可以在php中使用strtr函数,但这只返回一个布尔值。我也需要字符串。

4 个答案:

答案 0 :(得分: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"
}

答案 1 :(得分:1)

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

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

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

echo $matches[1] ;

$matches包含关键字的出现次数。 $matches[0]有完整的字符串,$matches[1]第一次出现,依此类推。

答案 2 :(得分: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可以避免大小写问题。


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

答案 3 :(得分:0)

您可以使用如下

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