使用 bash 或 php,如何检测文件中最后一个 php block 是否有结束标记,无论尾随换行符或空格如何?
这是我到目前为止所得到的,但我不知道如何确定结束标记后面的内容是否更多 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
错误:
<?php $var = 'value';
正确:
<?php $var = 'value'; ?>
正确:
<?php $var = 'value'; ?><!DOCTYPE>
正确:
<?php $var = 'value'; ?> <!DOCTYPE>
错误:
<?php $var = 'value'; ?> <!DOCTYPE> <?php $var = 'something';
错误:
<?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
最佳答案
感谢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 .
关于php - 如何检测关闭 php 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385404/