2010-11-30 3 views
3

저는 오늘 저의 프로젝트를 위해 마크 다운 변환기를 연구하고 있습니다. 나는 그것에서 길을 잃었고 단지 코드를 훑어 보았고 목록을 변환하는 데 막대한 돈이 있음을 알았다. 내 코드는 아래에 있습니다. 목록을 처리하는 코드를 제공했습니다. 코드 단축에 대한 제안과 함께 할 수 있습니다. 필자가 작성한 내용을 볼 수 없으며, 새로운 눈 쌍이 필요합니다. 목록을 위해 목록 형, 깊이와 문자열 배열을 만들고,PHP에서 마크 다운 목록을 HTML 목록으로 변환합니다.

<?php 

class Markdown { 

    private static $html = ''; 
    private static $list_types = array(
    array(
     '>>', 
     '<ul>', 
     '</ul>' 
    ), 
    array(
     '>>>', 
     '<ol>', 
     '</ol>' 
    ) 
); 
    private static $list_patterns = array(
    '/-[ ]+(.+)/' => ' >>\1', 
    '/[0-9]{1}\. (.+)/' => ' >>>\1' 
); 

    public static function convertText($markdown = array()) { 
    $markdown = explode("\n", strip_tags($markdown)); 
    foreach ($markdown as &$line) { 
     $line = htmlentities($line, ENT_QUOTES, 'UTF-8'); 
     foreach (self::$list_patterns as $pattern => $replace) { 
     if (!is_array($line) && preg_match($pattern, $line)) { 
      $para = false; 
      $line = preg_replace($pattern, $replace, $line); 
      $type = 0; 
      foreach (self::$list_types as $key => $val) { 
      if (preg_match('/ ' . $val[0] . ' /', $line)) 
       $type = $key; 
      } 
      $line = preg_split('/' . self::$list_types[$type][0] . '/', $line); 
      $line = array('depth' => strlen($line[0]), 'string' => $line[1], 'type' => $type); 
     } 
     } 
    } 

    while (!empty($markdown)) { 
     $snippet = array_shift($markdown); 
     if (is_array($snippet)) 
     self::makeList($snippet, $markdown); 
     else 
     self::$html .= $snippet; 
    } 
    return self::$html; 
    } 

    private static function makeList($snippet, &$markdown, $last_depth = 0, $close_tag = '') { 
    if ($last_depth == $snippet['depth']) 
     self::$html .= sprintf('</li><li>%s', $snippet['string']); 
    elseif ($last_depth < $snippet['depth']) 
     self::$html .= sprintf('%s<li>%s', self::$list_types[$snippet['type']][1], $snippet['string']); 
    elseif ($last_depth > $snippet['depth']) 
     self::$html .= sprintf('</li>%s<li>%s', $close_tag, $snippet['string']); 

    $next_snippet = array_shift($markdown); 
    if (is_array($next_snippet)) 
     self::makeList($next_snippet, $markdown, $snippet['depth'], self::$list_types[$snippet['type']][2]); 
    else 
     array_unshift($markdown, $next_snippet); 

    self::$html .= sprintf('</li>%s', $close_tag); 
    } 

} 

?> 

는 기본적으로 코드는 패턴 매칭을 많이 수행하고 목록을 제외한 모든 패턴은 배열 "$ 인하"의 문자열로 떠날 것이다. 텍스트 변환이 끝나면 "$ markdown"배열을 반복하고 다음 항목이 배열인지 아닌지를 검사하여 중첩 루프 구조를 만들 수 있습니다.

죄송합니다. 질문이 모호하게 보일 경우 미안합니다.로드를 작성한 것처럼 코드를 단축하는 방법에 대한 힌트를 원합니다. 사전

누가 복음

+9

야생에서 완전한 PHP 마크 다운 구현이 이미 실현되었습니다. BSD/GPL 라이센스를 받아서 소프트웨어에 임베드하면 문제가되지 않습니다. http://michelf.com/projects/php-markdown/ – ThiefMaster

+0

@ tief는 다음과 같이 말했습니다. 바퀴에 정말로 관심이 없다면, 바퀴를 재발 명하지 마십시오. – deceze

+0

나는이 클래스를 보았고 나에게 불필요한 것들을 모두 지운 후에 (나는 워드 프레스 등을 필요로하지 않는다) 여전히 1500 라인의 코드를 필요로한다. 나는 그 1500 라인에 상당한 논평이 있다는 것을 알고 있지만, 나는 그것이 더 작은 패키지에서 달성 될 수 있기를 바랬다. 그리고 이런 종류의 바퀴는 나를 위해 약간의 흥미를 가지고 있습니다. 댓글을 주셔서 감사합니다. – Luke

답변

0

을 즐길 수 있습니다. 코드를 작성하기 시작했지만 좋은 학습 경험.

2

@Theifmaster에서

덕분에 아마도 앞으로 더 나은 방법입니다. 그러나 2 줄의 코드와 사용되지 않은 변수 $ para를 제거했습니다. @Theifmaster는 michelf.com/projects/php-markdown 이미 포괄적이고 그래서 내가 정말 더 유용한 아무것도 추가 관리하지 않을했다로 사용 결국 끝내 말했듯이

<?php 

class Markdown { 

    private static $html = ''; 
    private static $list_types = array(
    array('>>','<ul>','</ul>'), 
    array('>>>','<ol>','</ol>') 
); 
    private static $list_patterns = array(
    '/-[ ]+(.+)/' => ' >>\1', 
    '/[0-9]{1}\. (.+)/' => ' >>>\1' 
); 

    public static function convertText($markdown = array()) { 
    foreach (explode("\n", strip_tags($markdown)) as &$line) { 
     $line = htmlentities($line, ENT_QUOTES, 'UTF-8'); 
     foreach (self::$list_patterns as $pattern => $replace) { 
     if (!is_array($line) && preg_match($pattern, $line)) { 
      $line = preg_replace($pattern, $replace, $line); 
      $type = 0; 
      foreach (self::$list_types as $key => $val) { 
      if (preg_match('/ ' . $val[0] . ' /', $line)) 
       $type = $key; 
      } 
      $line = preg_split('/' . self::$list_types[$type][0] . '/', $line); 
      $line = array('depth' => strlen($line[0]), 'string' => $line[1], 'type' => $type); 
     } 
     } 
    } 

    while (!empty($markdown)) { 
     $snippet = array_shift($markdown); 
     if (is_array($snippet)) 
     self::makeList($snippet, $markdown); 
     else 
     self::$html .= $snippet; 
    } 
    return self::$html; 
    } 

    private static function makeList($snippet, &$markdown, $last_depth = 0, $close_tag = '') { 
    if ($last_depth == $snippet['depth']) 
     self::$html .= sprintf('</li><li>%s', $snippet['string']); 
    elseif ($last_depth < $snippet['depth']) 
     self::$html .= sprintf('%s<li>%s', self::$list_types[$snippet['type']][1], $snippet['string']); 
    elseif ($last_depth > $snippet['depth']) 
     self::$html .= sprintf('</li>%s<li>%s', $close_tag, $snippet['string']); 

    $next_snippet = array_shift($markdown); 
    if (is_array($next_snippet)) 
     self::makeList($next_snippet, $markdown, $snippet['depth'], self::$list_types[$snippet['type']][2]); 
    else 
     array_unshift($markdown, $next_snippet); 

    self::$html .= sprintf('</li>%s', $close_tag); 
    } 

} 

+0

2 줄을 저장해 주셔서 감사합니다. +1 – Luke

관련 문제