【问题标题】:php explode something into array, but using values in betweenphp 将某些东西爆炸成数组,但使用介于两者之间的值
【发布时间】:2011-06-19 06:57:42
【问题描述】:

我有一个字符串我想清理并放入一个数组中,这样我就可以在 mysql 中搜索它。


// Here's one example of what the string might have:
$string1 = "(1) *value1* *value2*; (2) *value3* *value4* *value5*; (3) *value6*";
// And here's another possibility:
$string2 = "*value1* *value2* *value3* *value4*";

// I want to remove all the "(#)" stuff, and explode all the values into an array
// This is what I have so far:
// $string can be like the examples $string1 or $string2

$string_clean = str_replace("* *","",trim(preg_replace("/\((\d)\)/i", "", $string)));
$my_array = explode('*', trim($string_clean, '*'));

但是,这就是我得到的:

Array ( [0] => value1 [1] => [2] => value2 [3] => [4] => value3 [5] => [6] => value4 [7] => [8] => value5 ) 

我想我可以找到一个函数来从数组中删除所有空项,但我想知道是否有更有效的方法来做到这一点?

【问题讨论】:

  • 如果你的值不包含空格,你可以str_replace() away * 和 ;, preg_repalce() away (#) 然后explode() on " " 得到所有值。

标签: php arrays preg-replace explode


【解决方案1】:

你需要preg_match_all():

preg_match_all('#\*([^*]+)\*#', $string, $matches);
$result = $matches[1];
// $result is array('value1', 'value2', ...)

这将找到所有*something* 并返回* 之间的字符串。

【讨论】:

  • 谢谢你!我刚刚得到了一个有趣的结果,数组中的数组虽然
  • 是的,正如我所说,结果在 $matches[1] 中,而不是在 $matches 中:-)
  • 数组 ( [0] => 数组 ( [0] => value1 [1] => value2 [2] => value3 [3] => value4 [4] => value5 ) [1] => 数组 ( [0] => value1 [1] => value2 [2] => value3 [3] => value4 [4] => 值5 ) )
猜你喜欢
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多