I've decided that I want to properly learn how to use regular expressions. For one thing, they're very useful in programming projects. But they're also very cool, in a geeky kind of way. Just yesterday, I was trying to fix a problem I was having with a form processing situation using Fox when I discovered my elementary knowledge of regular expressions could actually come in handy. You see, I was beta testing a program proposal form, and I noticed that anyone typing smileys/emoticons :) or (: would break the form. Thus, I wrote the following filter for Fox.

  $FoxFilterFunctions['smiley'] = 'FoxSmileyFilter';
  function FoxSmileyFilter($pagename, $fields) {
    $fields = preg_replace('/\(:/', '(:', $fields);
    $fields = preg_replace('/:\)/', ':)', $fields);
    return $fields;
  }

What this does, in (more) plain English, is tell Fox to look and see if anyone has typed a smiley in any form field, and if so, to replace the parentheses used with their special character code equivalents. The regular expressions are used in the middle of the lines. Basically the 'single quotes' tell it I'm going to type a character string, putting things /in forward slashes/ tells it where the thing I'm looking for begins and ends, and then it's just (: and :)--but wait! Parentheses are special characters, so you have to escape them by putting a backslash in front so PHP won't try to interpret them as having some kind of deep meaning.

Anyhow, that was extremely simple in the grand scheme of things, so I have a lot to learn. ;)

Posted in



3 comments on "Regular Expressions"


Efriatan (http://www.redpizarra.org.bo/)
October 8th, 2007 at 4:59 pm

i don't understand very well its theme. Do you help me please?

Jon
October 12th, 2007 at 8:32 pm

I'm not sure what you mean by theme. You mean, what's the basic idea of regular expressions? I guess I didn't explain that very well. Basically, a regular expression is a way of discovering a string of text within a larger piece of text. So, for example:

The quick brown fox jumps over the lazy dog

Say you wanted the system to change all the foxes to bears, so you'd have to invent a way for the computer to find all the foxes. So

/fox/

so /fox/ is a regular expression that helps the computer discover every time fox appears. Of course, this would find the "fox" within Firefox, etc., so really they're a lot more complicated than this very simplistic example. So you wanted to replace it with bear... and to change it in PHP you could then use

$original = 'the quick brown fox jumps over the lazy firefox'; $fixed = preg_replace('/fox/', 'bear', $original);

so then $fixed would equal to 'the quick brown bear jumps over the lazy firebear'.

does that help?

Jon
December 3rd, 2007 at 9:53 pm

testing.


Add a comment

Name:
E-mail: (for gravatar only, not stored.)
Website: (e.g. google.com)
Type your comment
Type this number: 392