在字符串中查找字符串的出现

时间:2015-09-21 09:12:20

标签: php mysql

我试图找出一个字符串是否包含来自特定字符串表的任何字符串,并将找到的字符串分配给变量,然后将所述变量插入到数据库中。然而,即使有明显匹配,它似乎也无法找到匹配。任何帮助将不胜感激。

这是代码:

$stringToMatch = 'Good Morning';
$string_list = "SELECT string FROM strings";
$resultStringList = mysqli_query($link, $string_list) or   die(mysqli_error($link));
$string_name = "Test";
while ($row = mysqli_fetch_array($resultStringList)) {
if (stristr($StringToMatch, $row)) {
$string_name = $row;
} 
}
mysqli_query($link, "INSERT INTO table (string) VALUES ('$string_name')") or die(mysqli_error($link));

此时,表中显示的是"测试"在字符串列中。理想情况下,它应插入单词" Morning"相反,它可以在表字符串中找到

2 个答案:

答案 0 :(得分:0)

stristr()
  

返回从第一个开始并包括第一个的所有haystack   针的发生到最后。

您从查询中获取数组。因此需要将字符串传递给stristr函数以匹配

 while ($row = mysqli_fetch_array($resultStringList)) {
    if (stristr($StringToMatch, $row['string'])) {// need to pass string instead of array
    $string_name = $row['string'];// here pass string instead if array
    } 
    }

答案 1 :(得分:0)

$stringToMatch = 'Good Morning';

$string_list = "SELECT string FROM strings";
$resultStringList = mysqli_query($link, $string_list) or die(mysqli_error($link));

$string_name = "Test";
while ($row = mysqli_fetch_array($resultStringList)) {
   if(stristr($StringToMatch, $row['string'])){ // Here's your problem
      $string_name = $row['string']; // and here
   }
}
mysqli_query($link, "INSERT INTO table (string) VALUES ('$string_name')") or die(mysqli_error($link));