Reputation: 873
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?
Upvotes: 0
Views: 1536
Reputation: 32810
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 )
Upvotes: 1
Reputation: 13181
This should work:
[^-]+
But why use regexp at all? You can simply explode by "-"
Upvotes: 0
Reputation: 660
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
Upvotes: 0