开发者

Regex in PHP between /* & */ for preg-match

开发者 https://www.devze.com 2023-01-11 07:41 出处:网络
I am trying to extract all substrings in a string that is between the strings /* and */. I know this will probably need to be done with regular expressions however I\'m having a hard time getting the

I am trying to extract all substrings in a string that is between the strings /* and */. I know this will probably need to be done with regular expressions however I'm having a hard time getting the correct regex since the star character is actually used to symbolise repeated characters. I'm am trying to use the preg-match method in PHP here is what I have come up with so far but I'm not having much luck.

<?php
   $aString = "abcdef/*ghij*/klmn/*opqrs*/tuvwxyz";
   preg_match("/*/.*/", $aString, $anArray);

   for ($i = 0; $i < count($a开发者_开发问答nArray); i++)
      echo $anArray[i] . "\n";
?>


To extract comment sections out of PHP code, use the Tokenizer.

token_get_all() will parse the code, and return an array of elements.

Comments will be represented as T_COMMENT elements.

This has the great advantage of catching all possible ways of having comments in PHP code:

/* This way, */

// This way

# and this way


Working code:

 $aString = "abcdef/*ghij*/klmn/*opqrs*/tuvwxyz";

 // SIMPLE VERSION WHERE ASTERISK MAY NOT BE IN THE COMMENT
 // \/\* is just escape sequence for /*  
 // [^\*]* - in comment may be whatever except * (asterisk)
 // \*\/ is escape sequence for */
 preg_match_all("#\/\*[^\*]*\*\/#", $aString, $anArray);

 // BETTER VERSION 
 // http://www.regular-expressions.info/refadv.html - for explanation of ?: and ?!  
 preg_match_all("#\/\*" . "((?:(?!\*\/).)*)" . "\*\/#", $aString, $anArray);


 var_dump($anArray); // easier for debugging than for-loop

Output for better version:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "/*ghij*/"
    [1]=>
    string(9) "/*opqrs*/"
  }
  [1]=>
  array(2) {
    [0]=>
    string(4) "ghij"
    [1]=>
    string(5) "opqrs"
  }
}


Escape the * to use it, and ad parentheses to capture the content like that : /\*(.*)\*/, and you should use preg_match_all to find all matches in your string.

(and easier than a for, use var_dump($anArray))


$aString = "abcdef/*ghij*/klmn/*opqrs*/tuvwxyz";
preg_match_all("/\/\*(.*?)\*\//", $aString, $anArray,PREG_SET_ORDER);
var_dump($anArray);


If (as you say in one of the comments) you're attempting to display PHP code in HTML there's actually a built-in function (highlight_file) that does precisely this.

Free free to ignore if you're using this as a learning exercise, etc. :-)


I think the regex will be simple as

\/\*.*?\*\/

here's demo of a working code using regular expression tester

http://liveregex.com/WoDbk

0

精彩评论

暂无评论...
验证码 换一张
取 消