【问题标题】:How to detect closing php tag?如何检测关闭的php标签?
【发布时间】:2016-07-14 22:46:43
【问题描述】:

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

    <?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 中失败了,因为我不知道结束标记之后的内容是否更多。

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

【问题讨论】:

  • 只是好奇 - 你需要它做什么?将 php 与标记混合是一个文件是一件坏事。一旦更正,您应该只使用 php 文件,建议不要使用关闭 ?&gt; 反正就是这种情况
  • $str="?&gt;"; 怎么样,我看不出这将是 100% 可能的
  • 也许很有趣? php.net/manual/en/function.token-get-all.php 还有:github.com/nikic/PHP-Parser。另外:stackoverflow.com/questions/5586358/… 为什么?他们解析 PHP 并生成可能更容易识别您想要什么的输出?
  • @Ryan 感谢您提供的精彩链接!它们看起来确实很有帮助:)
  • @RyanVincent 再次感谢!!!在查看了token_get_all 的链接后,我只花了大约 15 分钟。我为其他人发布了我的答案。

标签: php bash line-endings


【解决方案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

【讨论】:

    猜你喜欢
    • 2011-03-12
    • 2021-10-06
    • 2018-01-09
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多