views:

298

answers:

1

I've been writing a plugin for Joomla that automatically processes HTML comments eg. {dropcap}B{/dropcap} and creates a drop cap style.

I needed a way to pass on parameters to the plugin so therefore decided the best way would be: {dropcap}B|FF00FF|00FF00{/dropcap}.

I created a function:

if (preg_match_all('/{dropcap}(.+?){\/dropcap}/', $row->text, $matches, PREG_PATTERN_ORDER) > 0)
{
  foreach ($matches[0] as $match)
  {
    $SimpleDropCapPlugin->html = "";
    $_temp = preg_replace("/{.+?}/", "", $match);
    $_params = explode('|', $_temp);
    $SimpleDropCapPlugin->text_dropcap = $_params[0];
    if ($_params[1])
      $SimpleDropCapPlugin->colour_border = '#' . $_params[1];
    if ($_params[2])
      $SimpleDropCapPlugin->colour_background = '#' . $_params[2];
    if ($_params[3])
      $SimpleDropCapPlugin->colour_text = '#' . $_params[3];
    if ($_params[4])
      $SimpleDropCapPlugin->font_size = $_params[4];
    if ($_params[5])
      $SimpleDropCapPlugin->font_family = $_params[5];

    $SimpleDropCapPlugin->html .= "<span style=\"border: 1px solid " . $SimpleDropCapPlugin->colour_border . "; background: " . $SimpleDropCapPlugin->colour_background . " none repeat scroll 0% 0%; margin-right: 6px; margin-top: 5px; float: left; color: " . $SimpleDropCapPlugin->colour_text . "; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; font-size: " . $SimpleDropCapPlugin->font_size . "px; line-height: 60px; padding-top: 2px; padding-right: 5px; font-family: " . $SimpleDropCapPlugin->font_family . ";\">";
    $SimpleDropCapPlugin->html .= strtoupper($SimpleDropCapPlugin->text_dropcap);
    $SimpleDropCapPlugin->html .= "</span>";


    $row->text = preg_replace( "#{dropcap}".$_temp."{/dropcap}#s", $SimpleDropCapPlugin->html , $row->text );
  }
}

If I use the '|' character the script works but creates a seperate dropcap each time the pipe character is used, whereas if I use a different seperator eg. ':' the script works fine.

I definitely want to use the pipe character as it is not usually used in HTML so therefore I can extend the usage of the plugin, is there any way to stop this strange behaviour?

+3  A: 

The problem is that '|' is a special character in regular expressions. You need to use preg_quote to escape it here:

$row->text = preg_replace( "#{dropcap}".preg_quote($_temp,'#')."{/dropcap}#s", $SimpleDropCapPlugin->html , $row->text );

Actually, there's no reason to even include $_temp in that regex, you could just do this:

$row->text = preg_replace( "#{dropcap}.+?{/dropcap}#s", $SimpleDropCapPlugin->html , $row->text );

Correction: upon closer examination, you do need to use $_temp, at least in your implementation, because you are replacing on a whole row of text which could have multiple droptags in it.

Kip