Learning to Use Regular Expressions by Example( part4)
Posted on January 29, 2008
by Blog.thegioiwebsite.Net Học thiết kế web với PHP |
Other uses
Extracting Parts of a String
ereg() and eregi() have a feature that allows us to extract matches of patterns from strings (read the manual for details on how to use that). For instance, say we want do get the filename from a path/URL string -- this code would be all we need:src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
ereg("([^\/]*)$", $pathOrUrl, $regs);echo $regs[1];
Advanced Replacing
ereg_replace() and eregi_replace() are also very useful: suppose we want to separate all words in a string by commas:ereg_replace("[ \n\r\t]+", ",", trim($str));
Some exercises
Now here's something to make you busy:
- modify our e-mail-validating regular expression to force the server name part to consist of at least two names (hint: only one character needs to be changed);
- build a function call to
ereg_replace()that emulatestrim(); - make up another function call to
ereg_replace()that escapes the characters'#','@','&', and'%'of a string with a'~'.
Have fun!
--Dario - DucManh
Comments
Leave a Reply