简体   繁体   English

将字符串中的正则表达式转换为数组

[英]regular expression on string into array

I'm new to regular expressions in PHP so I was wondering how would I split the below soe that all "somethings" are stored in an array? 我是PHP正则表达式的新手,所以我想知道如何将下面的代码拆分为所有“东西”都存储在数组中?

$string = "something here (9), something here2 (20), something3 (30)";

Desired result: 所需结果:

$something_array = array(
[0] => something 
[1] => something2
[2] => something3 ) 

Basically removing "," and whatever are in the brackets. 基本上删除“,”以及括号中的所有内容。

The regular expression would be something like this: (.*?) \\([^)]*\\),? 正则表达式将如下所示: (.*?) \\([^)]*\\),? It uses . 它用 。 (anything) because you requested so, but if it's a word you should use \\w instead, or if it's anything but whitespace \\S so it would be something like this: (\\S*) \\([^)]*\\),? (任何内容),因为您是这样要求的,但是如果是一个字,则应该改用\\ w,或者除了空格\\ S以外的任何内容,因此应该是这样的: (\\S*) \\([^)]*\\),?

Explaining the expression: 解释表达式:

  • (.*?) - match anything, but in lazy mode, or 'as little as possible' mode (.*?) -匹配任何内容,但在惰性模式或“越少越好”模式下
  • [^)]* - match anything but ) as many as possible [^)]* -尽可能匹配除以外的任何内容
  • \\([^)]*\\) - match a pair of brackets and it's content \\([^)]*\\) -匹配一对方括号及其内容
  • ,? - match a comma if it's there -如果有逗号则匹配

You can test it all these HERE 您可以在这里测试所有这些

Finally, using the preg_match_all PHP function, this would look something like this: 最后,使用preg_match_all PHP函数,它看起来像这样:

$str = 'something (this1), something2 (this2), something3 (this3)';
preg_match_all('/(\S*) \([^)]*\),?/', $str, $matches);
print_r($matches);

I wouldn't use regular expressions for something like this, but rather just PHP's explode() function. 我不会对此类东西使用正则表达式,而只会使用PHP的explode()函数。

$parts = explode(', ', $string);
$result = array_map(function($element) {
    return substr($element, 0, strrpos($element, ' '));
}, $parts);
print_r($result);

The above would output 以上将输出

Array
(
    [0] => something here
    [1] => something here2
    [2] => something3
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM