Click to See Complete Forum and Search --> : Help with Reg Expression
quadoc
04-22-2008, 11:22 AM
I've a string
$str = "name1@mail.com,name2@yahoo.com,name3,name4@gmail.com,name5"
and I want to append the "yahoo.com" to name3 and name5 above.
I can write a function to do this, but I know regular expression can solve this much simpler but I'm not quite know how to do it. Are there any Reg Exp guru guys out there can shed some light on this. Thanks...
you could use a regexp to look for the contents between the commas store them to an array with preg_match() then use preg_replace() to replace the contents it previously found. It's really not that hard with preg, it just doesn't make sense.
In this case I would explode the string on the comma to create the array. Loop through with foreach() and use strstr() to look for the '@' and if it doesn't exist append the yahoo.com.
regexps are cool but theres no advantage over explode() in this case.
NogDog
04-22-2008, 01:48 PM
For a preg_replace one-liner:
$str = preg_replace('/(?<=^|,)[^@]+(?=,|$)/', "$0@yahoo.com", $str);
quadoc
04-22-2008, 05:01 PM
Thanks NogDog! That is one line of sweet and neat code, that saves me quite a bit of coding... :)
I take it back that is cool.
Care to take us through what that does, I'm pretty good with regexps but that's beyond me!
NogDog
04-22-2008, 05:44 PM
I take it back that is cool.
Care to take us through what that does, I'm pretty good with regexps but that's beyond me!
The main aspect is the use of look-behind and look-ahead assertions to anchor the match.
(?<= start of look-behind assertion
^|, start of string assertion or a comma
) end of look-behind assertion
[^@]+ one or more occurrences of any character which is not "@"
(?= start of look-ahead assertion
,|$ comma or end of string assertion
) end of look-ahead assertion
PS: on further review, it should probably have an "Ungreedy" modifier added:
$str = preg_replace('/(?<=^|,)[^@]+(?=,|$)/U', "$0@yahoo.com", $str);
look-behind/ahead is new to me. I'll go have a read up.
Thanks