PHPBuilder - Regular Expressions Page 4

RSS Twitter

Regular Expressions - Page 4

by: Dario F. Gomes
July 30, 2000

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:
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 emulates trim();
  • make up another function call to ereg_replace() that escapes the characters '#', '@', '&', and '%' of a string with a '~'.
Have fun!

« Previous Page

Comment and Contribute

Your comment has been submitted and is pending approval.

Dario F. Gomes



(Maximum characters: 1200). You have characters left.