Forum Moderators: coopster
<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").
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);
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!