Hi! I'm a real Regular Expression noob but I need this for a project. I need to convert a string to variables. The string is composed by a phrase (one, two or three words), one number, a separator, one number, a phrase. So for example: South Africa 1-1 Argentina To "separate" the things I should use (correct me if I'm wrong) the ereg function...what is the regular expression that match that phrase? Thanks!
It would help to know how you would like it split up Give an example output that you would like it to end up as.
Yep sorry forgot about that The final result should be: South Africa-Argentina 1-1 Mean while I have (probably) found the correct RegEx: if (ereg ("([a-zA-Z ]+) ([0-9]{1,2})-([0-9]{1,2}) ([a-zA-Z ]+)", $title, $regs)) {... Code (markup): EDIT: @gustavorg: yes someting like that
Stay away from "ereg_*". Use "preg_*" instead. You can think of the ereg functions as depreciated preg functions. For this situation, the syntax will be about the same. you'll need to place pattern delimiters on either end of the pattern though. That pretty much consists of adding a # or ~ to the beginning and end of the pattern. http://www.php.net/preg_match
You can use ^(?P<team1>[A-Za-z\s]+) (?P<score1>\d+)\-(?P<score2>\d+) (?P<team2>[A-Za-z\s]+)$ Code (markup): which then even names the array keys correctly so for example $result = "South Africa 1-1 Argentina"; $pattern = '/(?P<team1>[A-Za-z\s]+) (?P<score1>\d+)\-(?P<score2>\d+) (?P<team2>[A-Za-z\s]+)/'; preg_match($pattern,$result,$out); echo '<pre>'.print_r($out, true).'</pre>'; PHP: As you can see, $out['team1'] is South Africa etc. And like joebert said, stay away from eregi Jay
Thanks for the replies. Does ereg and preg use the same syntax? So, can I substitute ereg with preg_match in the string I have wrote in the previous post or it won't work? I'm asking this because I have use ereg in many files, and now it's a bit hard to recode the whole thing. Thanks
Yes they have the same syntax (with extra arguments optional in preg_match that you wont need for your example). You will need to add a delimeter to either side of your regular expressions though, so if (ereg ("([a-zA-Z ]+) ([0-9]{1,2})-([0-9]{1,2}) ([a-zA-Z ]+)", $title, $regs)) //becomes if (preg_match("/([a-zA-Z ]+) ([0-9]{1,2})-([0-9]{1,2}) ([a-zA-Z ]+)/", $title, $regs)) PHP: Note the / on either side of the pattern now