php - 如何检测关闭 php 标签?

标签 php bash line-endings

使用 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
  1. 错误:

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

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

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

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

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

    <?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/

相关文章:

php - 使用 Slim 3 和内置 PHP 服务器路由参数

bash - 在 URL 中使用 Bash 变量会导致 "curl: (3) Illegal characters found in URL"

regex - Bash 正则表达式匹配点和字符

ruby - 如何确定 Ruby 中的行结束类型

PHP HTML 表单编码+签名?

PHP 字符串操作 : Extract hrefs

visual-studio-2010 - 如何修复整个 VS 解决方案不一致的行结尾?

PHPStorm 同步如何忽略行分隔符?

php - 打印编码字符串

bash - 重命名大量文件的扩展 Bash