All pastes #1364969 Raw Edit

Stuff

public text v1 · immutable
#1364969 ·published 2009-03-19 05:28 UTC
rendered paste body
<?php

class BBcode {
  /**
   * Parse BBcode into HTML.
   *
   * @param string $bbcode
   * @return string
   */
  public static function parse($bbcode)
  {
    $html = $bbcode;
    $e = create_function('$s', 'return htmlentities(str_replace("&gt;", ">", str_replace("&lt;", "<", $s)));');

    // convert < and > to their html entities
    $html = str_replace('<', '&lt;', $html);
    $html = str_replace('>', '&gt;', $html);

    // convert linebreaks to <br>
    $html = nl2br($html);

    // [url]
    $html = preg_replace('|\[url\](.+?)\[/url\]|ie', '\'<a href="\' . $e("$1") . \'">$1</a>\'', $html);
    $html = preg_replace('|\[url=(.+?)\](.+?)\[/url\]|ie', '\'<a href="\' . $e("$1") . \'">$2</a>\'', $html);

    // [img]
    $html = preg_replace('|\[img\](.+?)\[/img\]|ie', '\'<img src="\' . $e("$1") . \'">\'', $html);

    // [b], [i], [u]
    $html = preg_replace('|\[b\](.*?)\[/b\]|i', '<b>$1</b>', $html);
    $html = preg_replace('|\[i\](.*?)\[/i\]|i', '<i>$1</i>', $html);
    $html = preg_replace('|\[u\](.*?)\[/u\]|i', '<u>$1</u>', $html);

    // [youtube]
    $html = preg_replace('|\[youtube\]\s*(.+?)\s*\[/youtube\]|ie', 'self::youtube("$1")', $html);

    return $html;
  }

  /**
   * Get YouTube embed code
   *
   * @param string $url
   * @return string
   */
  private static function youtube($url)
  {
    $err['invalid_url'] = "<b>Youtube:</b> ongeldige url: <code>" . htmlentities($url) . "</code> ";

    if(!preg_match('|^http://(www\.)?youtube\.com/watch|i', $url))
      return $err['invalid_url'];

    // get query part
    $query = parse_url($url, PHP_URL_QUERY);

    if(!$query)
      return $err['invalid_url'];

    // parse query
    parse_str($query, $query_parts);

    if(empty($query_parts))
      return $err['invalid_url'];

    if(!isset($query_parts['v']))
      return $err['invalid_url'];

    // generate embed code
    $embed = '<object width="425" height="373"><param name="movie" value="http://www.youtube.com/v/{v}&rel=0&color1=0x006699&color2=0x54abd6&border=1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/{v}&rel=0&color1=0x006699&color2=0x54abd6&border=1" type="application/x-shockwave-flash" wmode="transparent" width="425" height="373"></embed></object>';

    $embed = str_replace('{v}', $query_parts['v'], $embed);

    return $embed;
  }
}