$re = '%(?:\bclass \w+\s*{\s*|\G(?!\A)\s*(?:(?://|#).*$|/\*[\s\S]*?\*/|\bconst[^;]*;)\s*)\K(\$\w+\s*(?:;|=.*;))%m';
$str = 'class MyClass {
$myvar1;
// some comment here (even with a variable $x;)
$myvar2;
/* I have a multiline comment here
with a variable $x; here
*/
$myvar3;
# Just another comment $x;
$myvar4;
const SOMETHING;
$myvar5;
function __construct($myvar1 = NULL, $myvar2 = array()) {
$this->myvar1 = $myvar1;
$this->myvar2 = $myvar2;
}
}';
$subst = "private $1";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php