문제

파일을 구문 분석하고 싶고 PHP와 REGEX를 사용하여 스트립을하고 싶습니다.

  • 빈 줄 또는 빈 줄
  • 한 줄의 주석
  • 멀티 라인 댓글

기본적으로 나는 포함 된 라인을 제거하고 싶습니다

/* text */ 

또는 멀티 라인 댓글

/***
some
text
*****/

가능하면 다른 동정인이 선이 비어 있는지 확인합니다 (빈 줄 제거)

그게 가능합니까? 누군가 나에게 그 일을하는 regex를 게시 할 수 있습니까?

정말 감사합니다.

도움이 되었습니까?

해결책

$text = preg_replace('!/\*.*?\*/!s', '', $text);
$text = preg_replace('/\n\s*\n/', "\n", $text);

다른 팁

구문 분석 파일에 이러한 조건과 일치하는 문자열이있는 경우 사용하는 모든 정규식이 실패합니다. 예를 들어,이를 바꿀 것입니다.

print "/* a comment */";

이것으로 :

print "";

아마도 ~ 아니다 당신이 원하는 것. 그러나 아마도 모르겠다. 어쨌든, Regexes는 기술적으로 그 문제를 피하기 위해 데이터를 구문 분석 할 수 없습니다. 현대 PCRE Regexes 가이 작업을 수행 할 수 있도록 많은 해킹을했기 때문에 기술적으로 말합니다. 정기적인 표현, 그러나 무엇이든. 인용문이나 다른 상황에서 이러한 것들을 제거하지 않으려면 본격적인 파서를 대신 할 수 없습니다 (여전히 간단 할 수 있음).

//  Removes multi-line comments and does not create
//  a blank line, also treats white spaces/tabs 
$text = preg_replace('!^[ \t]*/\*.*?\*/[ \t]*[\r\n]!s', '', $text);

//  Removes single line '//' comments, treats blank characters
$text = preg_replace('![ \t]*//.*[ \t]*[\r\n]!', '', $text);

//  Strip blank lines
$text = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $text);

그것 ~이다 가능하지만 나는 그것을하지 않을 것입니다. 필요한 공백 (문자열, 공백 키워드/식별자 (publicfuntionDostuff ()) 등)을 제거하지 않도록 전체 PHP 파일을 구문 분석해야합니다. 더 잘 사용합니다 토큰 화기 확장 php.

이것은 모든 / *를 * /로 대체하는 데 작동해야합니다.

$string = preg_replace('/(\s+)\/\*([^\/]*)\*\/(\s+)/s', "\n", $string);
$string = preg_replace('#/\*[^*]*\*+([^/][^*]*\*+)*/#', '', $string);

이것은 내 솔루션입니다. 다음 코드는 #에 의해 구분 된 모든 주석을 제거 하고이 스타일 이름 = vale에서 변수 값을 검색합니다.

  $reg = array();
  $handle = @fopen("/etc/chilli/config", "r");
  if ($handle) {
   while (($buffer = fgets($handle, 4096)) !== false) {
    $start = strpos($buffer,"#") ;
    $end   = strpos($buffer,"\n");
     // echo $start.",".$end;
       // echo $buffer ."<br>";



     if ($start !== false)

        $res = substr($buffer,0,$start);
    else
        $res = $buffer; 
        $a = explode("=",$res);

        if (count($a)>0)
        {
            if (count($a) == 1 && !empty($a[0]) && trim($a[0])!="")
                $reg[ $a[0] ] = "";
            else
            {
                if (!empty($a[0]) && trim($a[0])!="")
                    $reg[ $a[0] ] = $a[1];
            }
        }




    }

    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

이것은 좋은 기능이며 작동합니다!

<?
if (!defined('T_ML_COMMENT')) {
   define('T_ML_COMMENT', T_COMMENT);
} else {
   define('T_DOC_COMMENT', T_ML_COMMENT);
}
function strip_comments($source) {
    $tokens = token_get_all($source);
    $ret = "";
    foreach ($tokens as $token) {
       if (is_string($token)) {
          $ret.= $token;
       } else {
          list($id, $text) = $token;

          switch ($id) { 
             case T_COMMENT: 
             case T_ML_COMMENT: // we've defined this
             case T_DOC_COMMENT: // and this
                break;

             default:
                $ret.= $text;
                break;
          }
       }
    }    
    return trim(str_replace(array('<?','?>'),array('',''),$ret));
}
?>

이제 일부 변수에 포함 된 코드를 전달하기 위해이 기능을 사용합니다.

<?
$code = "
<?php 
    /* this is comment */
   // this is also a comment
   # me too, am also comment
   echo "And I am some code...";
?>";

$code = strip_comments($code);

echo htmlspecialchars($code);
?>

출력이 발생합니다

<?
echo "And I am some code...";
?>

PHP 파일에서로드 :

<?
$code = file_get_contents("some_code_file.php");
$code = strip_comments($code);

echo htmlspecialchars($code);
?>

PHP 파일로드, 댓글을 벗기고 다시 저장

<?
$file = "some_code_file.php"
$code = file_get_contents($file);
$code = strip_comments($code);

$f = fopen($file,"w");
fwrite($f,$code);
fclose($f);
?>

원천: http://www.php.net/manual/en/tokenizer.examples.php

나에게 더 잘 맞는 것을 발견했습니다. (\s+)\/\*([^\/]*)\*/\n* 멀티 라인, 탭 또는 댓글이 없거나 뒤에 간격이 제거됩니다. 이 동정인이 일치 할 댓글 예제를 남겨 둘 것입니다.

/**
 * The AdditionalCategory
 * Meta informations extracted from the WSDL
 * - minOccurs : 0
 * - nillable : true
 * @var TestStructAdditionalCategorizationExternalIntegrationCUDListDataContract
 */
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top