I am having problems trying to write a PHP Regex matching pattern to match and split string into needed groups.
Here is the situation... I have a multiple strings with contacts:
+35 00000000, info@company.com, www.company.com
This would give me:
Group 1: +35 00000000, info@company.com, www.company.com
+35 00000000, +360000000, info@company.com, www.company.com
This would give me:
Group 1: +35 00000000
Group 2: +36 00000000, info@company.com, www.company.com
info@company.com, www.company.com
This would give me:
Group 1: info@company.com, www.company.com
+35 00000000, info@company1.com, www.company1.com, +36 00000000, info@company2.com, www.company2.com
This would give me:
Group 1: +35 00000000, info@company1.com, www.company1.com
Group 2: +36 00000000, info@company2.com, www.company2.com
As you can see, these strings can be different. What I need to do is split those strings into groups of contacts, which:
So at first I tried to match groups starting with phone number and ending with website:
((\+?[\d ]+)?(, )?(.*)(, )?(www\.\w+\.\w{2,})?)
But this does not match exact. Also then tried to simplify everything ant match groups that start with phone numbers:
(\+[\d ]+).*
But this matches full strings.
Have to say I'm a big noob regarding Regex. I manage to do basic matchings, but this is too hard for me.
Length of pattern or low performance is not important as this will be a one-time execution.
You could get the matches using:
(?:\+?\d+(?:\h+\d+)*,\h*)?[^\s@]+@[^\s@,]+,\h*www\.\S+|\+?\d+(?:\h+\d+)*
The pattern matches:
(?:\+?\d+(?:\h+\d+)*,\h*)? Match an optional + then digits with optional spaces[^\s@]+@[^\s@,]+ Match an email like pattern only matching a single @,\h*www\.\S+ Match a , followed by www. and 1+ non whitespace chars| Or\+?\d+\h*\d+ Match the phone number like patternOr matching both ways for the url and the email address using an alternation |
(?:\+?\d+(?:\h+\d+)*,\h*)?(?:[^\s@]+@[^\s@,]+,\h*www\.\S+|\h*www\.\S+,\h*[^\s@]+@[^\s@,]+)|\+?\d+(?:\h+\d+)*
You can get the matches with expected groups using
(?=[^\s,])(\+?\d(?:[\d\s]*\d)?)?(?:(?:,\s*)?(\S+@\S+)\b)?(?:(?:,\s*)?(www\.\S+)\b)?
See the regex demo.
Note that (?=[^\s,]) lookahead is used to avoid matching empty strings.
Details:
(?=[^\s,]) - the next char must be a char other than a comma and whitespace(\+?\d(?:[\d\s]*\d)?)? - an optional Group 1: an optional +, a digit, and then an optional occurrence of zero or more digits and whitespaces and then a digit(?:(?:,\s*)?(\S+@\S+)\b)? - an optional occurrence of
(?:,\s*)? - an optional occurrence of a comma and zero or more whitespaces(\S+@\S+)\b - Group 2: one or more non-whitespaces, @, one or more non-whitespaces, a word boundary(?:(?:,\s*)?(www\.\S+)\b)? - an optional occurrence of
(?:,\s*)? - an optional occurrence of a comma and zero or more whitespaces(www\.\S+)\b - Group 3: www., one or more non-whitespaces, word boundary.