0

I have a little problem I need to sort. I want to either remove a part of a string or split it.

What I want to end up doing is splitting into 2 variables where I have "One, Two, Three" and "1, 2, 3" , I'm not sure if I can split it into two or if I have to remove the part after "-" first then do it again to remove the bit before "-" to end up with two variables. Anyways I have had a look and seems that preg_split() or preg_match() may work, but have no idea about preg patterns.

This is what I have so far :

$string = 'One-1, Two-2, Three-3';
$pattern = '????????????';
preg_match_all($pattern, $string, $matches);
print_r($matches);

EDIT: Sorry my Question was worded wrong:

Basically if someone could help me with the preg pattern to either split the Values so I have an array of One, Two Three and 1, 2, 3

----------------EDIT--------------

I have another question if I can, how would the preg_match change if I had this :

One Object-1, Two Object-2

So that now I have more than one word before the "-" which want to be stored together and the "1" on its own?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
snookian
  • 863
  • 6
  • 13
  • 35

3 Answers3

1

Try this :

$string = 'One-1, Two-2, Three-3';
$pattern = '/(?P<first>\w+)-(?P<second>\w+)/';
preg_match_all($pattern, $string, $matches);

print_r($matches['first']);
print_r($matches['second']);

Output:

Array ( [0] => One [1] => Two [2] => Three ) 
Array ( [0] => 1 [1] => 2 [2] => 3 ) 
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
  • Ahh, I tryed to simplify my question but created a wrong question :/ sorry! it, but I actually have an array which is One-1, Two-2, Three-3. And I want to end up with two arrays of One Two Three, and 1 2 3. Sorry for any confusion, I have used explode to split in into One-1 and Two-2 etc etc. – snookian Mar 22 '13 at 10:22
  • @user2194556 : your issue fixed ? – Prasanth Bendra Mar 22 '13 at 10:23
  • @user2194556 : Edited the answer as per your edit in your question. – Prasanth Bendra Mar 22 '13 at 10:30
  • I have another question if I can, how would the preg_match change if i had this "One Object-1, Two Object-2" So that know I have more that one word before the "-" which want to be stored together and the "1" on its own? – snookian Mar 22 '13 at 12:20
  • @user2194556 : try this : `$pattern = '/(?P([^,].*?))-(?P\d+)/';` I have not tested it. – Prasanth Bendra Mar 22 '13 at 12:28
  • Seems to work great, thank you soooo much again! You are a superstar. – snookian Mar 22 '13 at 12:33
0

If you always have a "-" use this instead:

$string = "One-1";
$args = explode("-", $string);
// $args[0] would have One
// $args[1] would have 1

You can read more about this function here: http://php.net/manual/en/function.explode.php

blamonet
  • 592
  • 1
  • 4
  • 13
0

This should work:

[^-]+

But why use regexp at all? You can simply explode by "-"

AdamL
  • 12,421
  • 5
  • 50
  • 74