【问题标题】:PHP matches against 2 stringsPHP 匹配 2 个字符串
【发布时间】:2018-08-21 14:26:01
【问题描述】:

我有 2 个字符串要比较。

$base_string =  "job, jobs, hiring, for hire, hire";
$user_string = "virtual assistant jobs";

if($user_string matches $base_string){
    return true; //true for jobs word
}else{
    return false;
}

根据上面的伪代码,你能帮我如何编码上面的逻辑吗?

【问题讨论】:

标签: php string match


【解决方案1】:
$base_string =  "job, jobs, hiring, for hire, hire";
$user_string = "virtual assistant jobs";

$array_match = explode(",",$base_string);
$array_search = explode(" ",$user_string);

if(sizeof(array_intersect($array_match,$array_search)) > 0){
    return true; //true for jobs word
}else{
    return false;
}

【讨论】:

  • 我的想法完全正确,如果需要的话 ;)
  • 应该使用preg_split 来表示逗号周围的可选空格,或者如果它们总是在那里,无论如何都应该包含它们。您的最后一行也可以是return count(array_intersect($array_match, $array_search)) > 0);
  • 删除空格:$array_match = array_map('trim', explode(",",$base_string));
  • 谢谢@dieter。这行得通。只需在爆炸分隔符参数中添加一个空格即可进行匹配。 $array_match = explode(", ",$base_string);
【解决方案2】:

你也可以这样做

<?php

$base_string =  "job, jobs, hiring, for hire, hire";
$user_string = "virtual assistant jobs";

$user_string = explode(" ", $user_string); //store the search string in a array to loop through with strpos

foreach ($user_string as $string_value){

  $string = $string_value;
  if (strpos($base_string, $string) !== false) {
        echo 'true';
  } else {
        echo 'false';
  }
}

【讨论】:

  • 我认为这不适用于带有“in my place”字样的 $user_string。在仍然会陷入其中并返回真实的结果。
猜你喜欢
  • 2013-12-28
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
  • 2011-09-04
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
相关资源
最近更新 更多