Fri Jun 9 21:47:56 CEST 2006

Regular Expressions

Today it's just another trip through the regular expressions on a PHP example. I had to replace the <input>-tags in HTML by <span>-tags because of html2pdf (which is another story *g*).

Let's begin. My <input>-tags are in the format

<input name="$NAME" value="$VARIABLE" style="margin-left:60px;">
and should be
<span>$VARIABLE</span>

On the first run I will replace all <input by <span:

$HMTL = ereg_replace('<input', '<span', $HTML);
After it I delete all name="$NAME" - where $NAME contains alphanumeric characters, a '_' or a space:
$HTML = ereg_replace('name="[a-z||0-9||_]*" ', '', $HTML);
Furthermore I need to remove the style=, because I don't need it in the output any more. The value of margin-left: could be only any numeric character, so I use:
$HTML = ereg_replace('style="margin-left:[0-9]+px;"', '', \$HTML);
Then I write the correct value. I devide the string into 3 parts. Part one is value=", the second part is my correct value (my regular expression) and the last part is the ending ". My value could be any alphanumeric character and the characters _ . : - and a space. After it I write the value between the <span> tags:
$HTML = 
  ereg_replace('(value=")([A-z||0-9||_||\.||:||\ ||-]*)(")', 
              '>\2</span', $HTML);
In the end I will try to set a fancy output:
$HTML = ereg_replace('<span >' , '<span>' , $HTML);
$HTML = ereg_replace('</span >', '</span>', $HTML);

In most of cases you'll need to escape the " in your ereg_replace functions (if you really use it to replace something of HTML code)...

If you want to have an additional look at something about regular expressions I suggest the manpage of awk.


Posted by Sebastian Wieseler | Categories: general |