#native_company# #native_desc#

Regular Expressions Page 4

By Dario F. Gomes
on 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(“[ nrt]+”, “,”, 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!