0

I'm trying to parse strings in PHP and store substrings into an array. The format of the string is as follows:

@SomeText1 ;SomeText2 $SomeText3 #SomeText4

(the "SomeText" substrings will never include the @;$# characters, so that's not a concern)

I want to extract SomeText1, SomeText2, ... separately using PHP, but there's a catch. Everything from the ";" is optional. So some example strings could be:

@ SomeText1 ; SomeText2 
@ SomeText1 # SomeText4
@ SomeText1 $ SomeText3 # SomeText4

I'm at a complete loss on how to do this.

I've tried searching here for an answer to this but the closest I could find is (Matching an optional substring in a regex) and (Regex to capture an optional group in the middle of a block of input), but I failed when trying to apply that to my case.

Thank you very much in advance.

Community
  • 1
  • 1
user3208442
  • 3
  • 1
  • 1

3 Answers3

0

You can use this regex in preg_match function call:

'/@ *(\w+)(?: *; *(\w+))?/'

And look for matches[1] and matches[2] for your 2 strings (matching groups).

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

So long as the order is consistent, you can do this:

preg_match("((@\S+)\s*(;\S+)?\s*(\$\S+)?\s*(#\S+)?)",$input,$matches);

Now, $matches is:

$matches = array(
    "@SomeText1",
    ";SomeText2" or null if it wasn't there,
    "$SomeText3" or null if it wasn't there,
    "#SomeText4" or null if it wasn't there
);

HTH

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

One way is to use preg_split:

$array = preg_split('/\s*[;$#]\s*/', $text);

You can also add a @ in there and ignore the first element if you want to remove it:

$array = preg_split('/\s*[@;$#]\s*/', $text);
array_shift($array);
Qtax
  • 33,241
  • 9
  • 83
  • 121