2
Hello,
I have a project that uses file_get_contents();
on an external page and would like to know how I can remove for example all lines starting with //
.
The external page contains Javascript comments and I haven’t found anything that can only remove comments within the tag.
Example of external page code;
<!DOCTYPE html>
<html>
<body>
<script>
[...]
// Alerta
alert('Olá!');
[...]
</script>
</body>
</html>
Code I tried to use to remove comments;
$html = explode(PHP_EOL, file_get_contents('https://example.com/'));
foreach($html as $linha) {
if(substr($linha, 0, 2) !== '//' && mb_substr($linha, 0, 2) !== '//') {
$linhas[] = trim($linha);
}
}
$html = implode(PHP_EOL, $linhas);
echo $html;
When I ran the script by the browser to see if you removed the comment or not, unfortunately I still got the comment.
I’m using XAMPP in the version 5.6.35
.
It would be important to explain the "I didn’t succeed" better, and how you tested the output. Also, it does not make much sense to use substr E mb_substr in the test, mainly because the characters are not multibyte. I still think it would be good to make a
trim
in the string, if you want to delete comments that are not in the first position– Bacco
I used
substr
along withmb_substr
just to make sure there was no mistake, but it didn’t turn out like I thought haha.– Amanda
Try to print_r each line (without the '/' test) to make sure the text is coming as you imagine, and the explode is happening in the right place.
– Bacco
I don’t think PHP_EOL is the best criterion in the explode, because it may be CRLF on your platform, but only CR or LF at the origin. I would probably prefer
explode( chr(10), file_get_contents ....
, orexplode( "\n", file_get....
– Bacco