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?

$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.

link|improve this question

feedback

2 Answers

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*) \([^)]*\),?

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:

$str = 'something (this1), something2 (this2), something3 (this3)';
preg_match_all('/(\S*) \([^)]*\),?/', $str, $matches);
print_r($matches);
link|improve this answer
I wrote the same regex, but you were 1 min faster. +1 for the explanation and the recommendation for the other character classes – ZombieHunter 53 mins ago
feedback

I wouldn't use regular expressions for something like this, but rather just PHP's explode() function.

$string = "something (this1), something2 (this2), something3 (this3)";
$parts = explode(', ', $string);
$result = array_map(function($element) {
    return current(explode(' ',$element));
}, $parts);
print_r($result);

The above would output

Array
(
    [0] => something
    [1] => something2
    [2] => something3
)
link|improve this answer
I understand this the most as expressions are still very confusing to me but this only works if something is one word. How would I get the below to work: something here(10), something (20), something here again(30) – user971824 29 mins ago
I have edited my origional example because I am having problems with using multiple words followed by numbers inside the brackets e.g.: book label (30), book label2 (100) – user971824 10 mins ago
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.