Split a string in substring with regular expression

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
nkamp
Forum Newbie
Posts: 3
Joined: Sat Aug 31, 2013 7:48 am

Split a string in substring with regular expression

Post by nkamp »

This is my string:

Game: club 1 - Club2, Result: 4 - 2, Set: 2-1, 3-1, 2-1

I want to break these by a PHP preg_match in the next peaces:
- 1: club 1 - Club2
- 2: 4 - 2
- 3: 2-1
- 4: 3-1
- 5: 2-1

The length depends a little because it can be 3 sets but also 5 sets.

I have tried this:
$regex = "#Game: (.*)(\s\-\s)(.*),#"

I tried some more alternatives but it doesn't give the result what I like.

But that doesn't give me the result what I want.

Can somebody give me an idea how to get this result? It may also in three steps like:
1 step only: [0] Club 1 - Club 2
2 step result: [0] 4 -2
3 step set: [0] 2-1 [1] 3-1

Nico
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Split a string in substring with regular expression

Post by Celauran »

explode() seems like a better choice than regular expressions here.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Split a string in substring with regular expression

Post by Christopher »

Yes, explode()ing on space and then reassembling the parts might be easier. Use trim(), rtrim(), ltrim() to remove commas.
(#10850)
nkamp
Forum Newbie
Posts: 3
Joined: Sat Aug 31, 2013 7:48 am

Re: Split a string in substring with regular expression

Post by nkamp »

Yes, I did it with explode.

Thanks.
Post Reply