-2

I'm trying to use preg_split to split this text

Yes, it was great. [I have no ideas how great it was.]

into this array:

['Yes', 'it', 'was', great', '[I have no ideas how great it was.]'

But I don't know how...

Duy Hoang
  • 25
  • 4
  • 5
    What if the square brackets contain square brackets as well? – Willem Van Onsem Jul 09 '18 at 23:20
  • Do you want to do this in Python or in PHP? – a_guest Jul 09 '18 at 23:26
  • What is `preg_split` ? – John Gordon Jul 09 '18 at 23:28
  • 2
    @JohnGordon Based on what I remember of PHP naming, it's the PHP equivalent of Python's `re.split`. (The `preg_*` functions are the regex functions that come from PCRE, as opposed to `ereg_*` for POSIX extended regex and `reg_*` for some builtin functionality that nobody should ever use.) – abarnert Jul 09 '18 at 23:30
  • We could assume that the square brackets don't contain square brackets. I just need the regular expression used to split the strings, so i think any language would be fine – Duy Hoang Jul 09 '18 at 23:32
  • 1
    @abarnert Correct and in PHP, POSIX has been depreciated in later versions. So pretty much exactly like `re.split()`. – Xorifelse Jul 09 '18 at 23:34
  • why is this tagged python? – Joran Beasley Jul 09 '18 at 23:37
  • @Xorifelse It looks like `ereg_` is deprecated as you said, and `reg_` is long gone, so… good news for people stuck using PHP, I guess. :) – abarnert Jul 09 '18 at 23:37
  • @DuyHoang; you think bad, each language has these own methods with eventually different behaviours. As an aside, using a split method is the bad way. It's easier to build a pattern for a global match ( `preg_match_all` with PHP, or `re.findall` with Python) – Casimir et Hippolyte Jul 09 '18 at 23:41
  • `preg_split()` seems like the wrong tool for this. – Barmar Jul 10 '18 at 00:12

1 Answers1

1
$keywords = preg_split("/[\s,.]+(?![^[]*])/", "Yes, it was great. [I have no ideas how great it was.]");
print_r($keywords);
Leprechaun
  • 759
  • 5
  • 14
  • 2
    There would be a chance for a huge benefit if you'd explain what you are doing here. – Jeff Jul 09 '18 at 23:33
  • 1
    I tried to write a simple explanation for 15 minutes, but failed. Found almost same problem already solved and explained. Hope it helps. https://stackoverflow.com/a/19414553/1921796 – Leprechaun Jul 09 '18 at 23:50