开发者

Testing for a backslash in a string

开发者 https://www.devze.com 2023-01-31 21:18 出处:网络
So I\'m writing a PHP script that will read in a CSS file, then put the comments and actual CSS in separate arrays. The script will then build a page with the CSS and comments all nicely formatted.

So I'm writing a PHP script that will read in a CSS file, then put the comments and actual CSS in separate arrays. The script will then build a page with the CSS and comments all nicely formatted.

The basic logic for the script is this:

  • Read in a new line
  • If it starts with a forward slash or ends with an opening bracket, set a bool for CSS or comments to true
  • Add that line to the appropriate element in the appropriate array
  • If the last character is a backslash (end of a comment) or the first character is a closing bracket (end of a CSS ta开发者_运维技巧g), set necessary bool to false
  • Rinse, repeat

If someone sees an error in that, feel free to point it out, but I think it should do what I want.

The tricky part is the last if statement, checking if the last character is a backslash. Right now I have:

if ($line{(strlen($line) - 3)} == "\\") {do stuff}

where $line is the last line read in from the file. Not entirely sure why I have to go back 3 characters, but I'm guessing it's because there's a newline at the end of each string when reading it in from a file. However, this if statement is never true, even though there are definitely lines which end with slashes. This

echo "<br />str - 3: " . $line{(strlen($line)-3)};

even returns a backslash, yet the if statement is never trigged.


That would be because $line{(strlen($line) - 3)} in your if statement is returning one backslash, while the if statement is looking for two. Try using

substr($line, -2)

instead. (You might have to change it to -3. The reason for this is because the newline character might be included at the end of the string.)


@mcritelli: CSS comments look like /* comment */ though, so just searching for a backslash won't tell you if it's starting or ending the comment. Here's a very basic script I tested which loops through a 'line' and can do something at the beginning and end of a comment --

<?php
$line  = "/* test rule */";
$line .= ".test1 { ";
$line .= "  text-decoration: none; ";
$line .= "}/* end of test rule */";

for ($i = 0; $i < strlen($line); $i++) 
{
    if ($line[$i] . $line[$i + 1] == "/*")
    {
        // start of a comment, do something
    }
    elseif ($line[$i] . $line[$i + 1] == "*/")
    {
        // end of a comment, do something
    }
}
?>
0

精彩评论

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

关注公众号