Forum Moderators: coopster

Message Too Old, No Replies

Help with regular expression using preg_match_all

         

housecor

3:03 am on Apr 8, 2006 (gmt 0)

10+ Year Member



I was hoping you guys could help me out with a regex that's driving me nuts. I'm allowing users to include images on my site by using a simplistic style of image tag:

<PIC 4 C>

So I need to use a regex to convert it to:

<IMG SRC="PIC4.JPG" ALIGN="CENTER">

My current expression: "/<PIC [0-9]+ [A-Z]>/";

And here's my actual code:
$pattern = "/<PIC [0-9]+ [A-Z]>/";
$subject = "<PIC 4 C>";
preg_match_all("$pattern",$subject,$pic_tag_array,PREG_SET_ORDER);
print $pic_tag_array[0][0]

The print above doesn't output anything, so it appears my regular expression is flawed. Any advice you guys can give would be really appreciated!

Also, to clarify, the number 4 in the example can actually be any length integer, and the C at the end that represents "center" alignment in this case, can also be R (for "right") or L (for "left").

coopster

2:16 pm on Apr 8, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



preg_replace_callback [php.net] would work well here. Create an array of the valid alignment "codes" and use them to set the attribute value in your <img> element.
function replaceImage($matches) 
{
$align = array(
'C' => 'CENTER',
'L' => 'LEFT',
'R' => 'RIGHT'
);
return '<IMG SRC="PIC' . $matches[1] . '.JPG" ALIGN="' . $align[$matches[2]] . '">';
}
$subject = "<PIC 4 C>";
$pattern = "/<PIC ([0-9])+ (C¦L¦R)>/";
$subject = preg_replace_callback($pattern, 'replaceImage', $subject);

I modified the pattern to only match when the alignment value is one that we expect (C or L or R). If you copy/paste, don't forget that the forum breaks the pipe symbol and you will need to rekey it.

housecor

4:21 am on Apr 10, 2006 (gmt 0)

10+ Year Member



Wow coopster, that worked like a charm! Thanks for taking the extra time to write out the code. I really appreciate it! I wasn't aware of this function but it's a perfect fit for what I was looking to do. You made my day! :)

coopster

11:36 am on Apr 10, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Well, you had already written out a snippet of the code and gave your best attempt -- it shows initiative on your part and the desire to learn how to get to the next level. We appreciate that [webmasterworld.com] in the PHP Forum. I just helped you understand your options.

callback functions can either be predefined PHP functions or they can by user-defined. This was a perfect place for a user-defined function. You'll find that PHP offers quite a few callback function options in addition to preg_replace_callback so now you know they exist and you have an idea of how they can be used!