2016-07-14 143 views
1

使用bash或php,如何检测文件中最后一个php块是否有结束标记,而不管尾随换行符或空格?如何检测关闭php标签?

这就是我到目前为止,但我无法弄清楚如何确定是否结束标记之后是更多的PHP或不。

#!/bin/bash 
FILENAME="$1" 
closed=false 

# just checking the last 10 lines 
# should be good enough for this example 
for line in $(tail $FILENAME); do 
    if [ "$line" == "?>" ]; then 
    closed=true 
    else 
    closed=false 
    fi 
done 

if $closed; then 
    exit 1 
else 
    exit 0 
fi 

我用测试运行器脚本编写了一些测试。

#!/bin/bash 
for testfile in $(ls tests); do 
    ./closed-php.bash tests/$testfile 
    closed=$? 
    if [ $closed -eq 1 -a "true" == ${testfile##*.} ] || 
    [ $closed -eq 0 -a "false" == ${testfile##*.} ]; then 
    echo "[X] $testfile" 
    else 
    echo "[ ] $testfile" 
    fi 
done 

您可以clone these files,但这是我到目前为止。

. 
├── closed-php.bash 
├── test.bash 
└── tests 
    ├── 1.false 
    ├── 2.true 
    ├── 3.true 
    ├── 4.true 
    ├── 5.false 
    └── 6.false 
  1. FALSE:

    <?php 
    $var = 'value'; 
    
  2. TRUE:

    <?php 
    $var = 'value'; 
    ?> 
    
  3. TRUE:

    <?php 
    $var = 'value'; 
    ?><!DOCTYPE> 
    
  4. TRUE:

    <?php 
    $var = 'value'; 
    ?> 
    <!DOCTYPE> 
    
  5. FALSE:

    <?php 
    $var = 'value'; 
    ?> 
    <!DOCTYPE> 
    <?php 
    $var = 'something'; 
    
  6. FALSE:

    <?php 
    $var = 'value'; 
    ?><?php 
    $var = 'something'; 
    

我没有3 & 4,因为如果我想不通在结束标记更多的PHP之后。

[X] 1.false 
[X] 2.true 
[ ] 3.true 
[ ] 4.true 
[X] 5.false 
[X] 6.false 
+1

只是好奇 - 你需要什么?混合PHP和标记是一个文件是坏事。一旦这个问题得到解决,你应该只需要使用php文件,并且建议不要使用关闭'?>'无论如何都是这样的情况 –

+0

除非插入PHP – Jonathan

+1

'$ str =“?>”'我不能请记住,这将是完全可能的 – 2016-07-14 23:01:30

回答

1

由于Ryan Vincent's comment,这是很容易使用token_get_all

<?php 
$tokens = token_get_all(file_get_contents($argv[1])); 
$return = 0; 
foreach ($tokens as $token) { 
    if (is_array($token)) { 
    if (token_name($token[0]) === 'T_CLOSE_TAG') 
     $return = 0; 
    elseif (token_name($token[0]) === 'T_OPEN_TAG') 
     $return = 1; 
    } 
} 
exit ($return); 

的时候我甚至增加了一些更多的测试,你可以see the full solution here