...

View Full Version : BBcode tags with optional parameters!



Sicton
06-19-2005, 02:11 PM
Does anyone know how would you define a BBcode tag with optional parameters? E.g. using preg_replace having [image align=right width=200] but making it so one or more parameters can be ignored or the order of them can be changed without writing loads of combinations of preg_replace code?

At the moment I have some regex like:

'#\[image align=(.*?) width=(.*?) height=(.*?)\]#msi'

but obviously the problem with that is all the parameters have to be entered or else it won't be picked up.

marek_mar
06-19-2005, 11:31 PM
Try this as regex:


#\[image(?: align=(.*?))?(?: width=(.*?))?(?: height=(.*?))?\]#msi

Sicton
06-20-2005, 12:52 AM
Fantastic. Thank you very much. :thumbsup:

I would say it would be good if the order of the parameters could be changed as well but that may be asking a little too much as this does the job fine so long as users remember the correct order.

marek_mar
06-21-2005, 10:54 AM
I was bored...


<?php
$data = '[image height=542 width=542 align=left foo=bar]\n[image width=542 height=542]\n[image]';
$valid_args = array('align', 'width', 'height');
$preg = '/(?>\[image)';
for($i = 0, $n = count($valid_args); $i < $n; $i++)
{
$preg .= '(?: (.*?)=(.*?))?';
}
$preg .= '\]/sim';
preg_match_all($preg, $data, $match, PREG_PATTERN_ORDER);
for($j = 0, $m = count(array_shift($match)); $j < $m; $j++)
{
for($i = 0, $n = count($match); $i < $n; $i += 2)
{
if(empty($match[$i][$j]))
{
unset($match[$i][$j]);
}
if(in_array($match[$i][$j], $valid_args))
{
$args[$j][$match[$i][$j]] = $match[$i + 1][$j];
if($i == $n - 2)
{ // You should validate the values in some way... a tab might be used but I don't wan't to use another regex for that.
$args[$j][$match[$i][$j]] = substr($match[$i + 1][$j], 0, strpos($match[$i + 1][$j], ' '));
}
}
else
{
unset($match[$i][$j], $match[$i + 1][$j]);
}
}
}
print_r($args);
?>

... and it was a challenge :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum