php 将某些内容分解为数组,但使用之间的值

发布于 2024-10-15 18:14:37 字数 855 浏览 3 评论 0原文

我有一个字符串想要清理并放入一个数组中,以便我可以在 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 ) 

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

I have a string I want to clean up and put into an array so that I can search through it in 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, '*'));

However, this is what I'm getting:

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

I suppose I could just find a function to remove all empty items from the array, but I'm wondering if there's a more effective way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁的新欢旧爱 2024-10-22 18:14:37

您需要preg_match_all()

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

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

You need preg_match_all():

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

This will find all *something* and return the strings between the *.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文