blogですかい

仕事、プライベートで学んだことなどを発信し、その内容がたとえ少数でも誰かの役に立ったらなら、それはとっても嬉しいなって

【PHP】正規表現の書いてある行をコメントアウトするときの注意


<?php
$html = file_get_contents('http://example.com/foo.html');
$html = preg_replace('@.*?<table.*?>@s','',$html);

上記のプログラムは特に問題無く動くのですが


<?php
$html = file_get_contents('http://example.com/foo.html');
//$html = preg_replace('@.*?<table.*?>@s','',$html);

このように 「*?>」 を含む行を 「//」 や 「#」 でコメントアウトすると、
?>をPHPの終了タグとみなされてしまいます。
(その後に続く@s','',$html);が標準出力に出力される)


<?php
$html = file_get_contents('http://example.com/foo.html');
/*
$html = preg_replace('@.*?<table.*?>@s','',$html);
*/

このように「/* 〜 */」でブロックコメントに入れてしまえば大丈夫でした。

検証環境
PHP 4.4.7 cli
PHP 5.2.6 cli
PHP 5.3.10 cli

追記 11/22/2012 19:07
公式マニュアルに書いてあった
The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: