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
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?
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 )