php - 使用通配符搜索mysql并将结果放入php数组

标签 php mysql

假设我有 this is the RED colorthis is the BLUE colorthis is WHATEVER color 作为不同部分的外观它们属于的句子,在我的 mySQL 数据库的表 tablecolumn 列的不同单元格中,或者在这个表的同一行中。

----------------------------------------------------------------------------------------
| column                                                                               |
----------------------------------------------------------------------------------------
| Look, this is the red color which is is not a nice one.                              |
----------------------------------------------------------------------------------------
| And this is the blue color, I like it more.                                          |
----------------------------------------------------------------------------------------

我怎样才能在数据库中搜索 this is the % color 进行精确匹配并将结果放入 PHP 数组中,以便我可以精确地 喜欢

  1. this is the RED color

  2. this is the BLUE color

  3. this is WATEVER color

跳过相应句子的所有其他部分?我的意思是我只需要将 this is the CURRENT_WILDCARD_VALUE color 的每次出现都放入数组中,仅此而已。

到目前为止,我有以下 PHP 代码

global $wpdb;
$query = $wpdb->get_results( "SELECT * FROM table WHERE row LIKE '% this is the % color %'");
print_r($query);

它会返回大量额外数据,而我需要它仅返回我的搜索词,同时牢记它使用的通配符。

最佳答案

一旦您从 MySQL 中选择了您的值。通过 preg_match() 传递每个记录值。大致如下所示:

$myValue = 'Look, this is the red color which is is not a nice one.'; // Value from MySQL
$matches = array();
preg_match ('/this is the (.+) color/', $myValue, $matches);

$matches 的值应该是:

array (
  0 => 'this is the red color',
  1 => 'red',
)

如果您随后想要保留一组唯一值(例如红色),最简单的方法是将每个 $matches[1] 存储为数组键。例如

$myColors = array(); // Put this before record iterator
$myColors[$matches[1]] = $matches[0];

这将产生一个数组:

array (
  'red' => 'this is the red color',
  'blue' => 'this is the blue color',
)

关于php - 使用通配符搜索mysql并将结果放入php数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42182447/

相关文章:

mysql - 如何添加在同一表中的另一列上递增的列?

php - 如何使用 PHP 从 MySQL 表的一个列中选择多个值

mysql - 按 IN 子句中匹配值较多的行排序

sql - 我如何着手处理新闻文章在主要、特色和类别区域方面的转移?

PHP:不可变的公共(public)成员字段

php - 如何限制用户只能向MySQL插入数据1次

php - Controller 中的 if else 语句在 Laravel 中没有响应

mysql - Vb.net Mysql 一份数据中多次查询

php - 使用 PHP 更新数据库

php - 为什么在 PHP 中使用 $_FILES 时出现未定义的数组键并尝试访问 null 类型值的数组偏移量错误