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

时间:2017-02-11 23:26:51

标签: php mysql

假设我在列的不同单元格中显示this is the RED colorthis is the BLUE colorthis is WHATEVER color作为其所属不同句子的一部分我的mySQL数据库的表,如果是这个表,则在同一行。

----------------------------------------------------------------------------------------
| 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. 这是RED颜色

  2.   
  3. 这是蓝色

  4.   
  5. 这是WATEVER颜色

  6.   

跳过相应句子的所有其他部分?我的意思是我只需要在这个是CURRENT_WILDCARD_VALUE颜色的每一个外观中都放入数组中。

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

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

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

2 个答案:

答案 0 :(得分:1)

从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]存储为数组键。 E.g。

$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',
)

答案 1 :(得分:1)

最后,我最终得到了以下似乎符合我期望的代码:

@Resource

我在此示例中严格将global $wpdb; // setting up the database search term $srchtrm = "green"; // querying WP database for matches and putting their parent cells into array $query = $wpdb->get_results(" SELECT post_content FROM wp_posts WHERE post_content REGEXP 'This is the $srchtrm color' "); // simplifying the query resulting array foreach ($query as $value) {$simplified_array[] = $value->post_content;} // avoiding php's Warning: implode(): Invalid arguments passed in if (empty($simplified_array)) {} // converting the simplified array into a single text string else {$textstring = implode(" ", $simplified_array);} // searching the above text string for matches and putting them into array preg_match_all('/This is the '.$srchtrm.' color/', $textstring, $matches); // removing repeating items in simplified array $simplifiedmatches = array_unique($matches[0]); // sorting the simplified matches array asc sort($simplifiedmatches); // outputting values foreach($simplifiedmatches as $match) {echo $match.'<br />';} 设置为green值,但$srchtrm实际上是一个动态变量,所以一切正常,我不是要创建一个数组只有一把钥匙。

代码是否一切正常,或者可能存在一些隐藏(对我来说)错误?