首页 > 解决方案 > Bash 到 php 正则表达式

问题描述

我有一个 bash 脚本,它尾随包含“CONNECT”或“DISCONNECT”的字符串的文件。一旦找到这样的字符串,该字符串就会通过管道传输到 php 脚本。

这是 bash 脚本:

tail -f -n 1 /var/log/connections | grep -P -0 --line-buffered "\bCONNECTED\b|\bDISCONNECTED\b" | php -f $SCRIPT_DIR/connections.php

这是php脚本:

#!/usr/bin/php
<?php

while ( false !== ( $connection_status = fgets ( STDIN ) ) )
{
    $get_status = preg_match ( "/\bCONNECTED\b|\bDISCONNECTED\b/", @$connection_status, $status_match ) ;

    foreach ( $status_match as $status )
    {
        switch ( $status )
        {
            case "CONNECTED": //If the string that got passed to this script (from the BASH script) contains CONNECTED
            {
                print ( "we are connected\r\n" ) ;
            }
            case "DISCONNECTED": //If the string that got passed to this script (from the BASH script) contains DISCONNECTED
            {
                print ( "we are disconnected\r\n" ) ;
            }
        }
    }
}
?>

DISCONNECT按预期工作,但使用CONNECT它返回"we are connected""we are disconnected"

标签: phpregexbash

解决方案


每个都case需要 abreak来阻止它运行,而不是{}.

case "CONNECTED": //If the string that got passed to this script (from the BASH script) contains CONNECTED
     print ( "we are connected\r\n" ) ;
break;
case "DISCONNECTED": //If the string that got passed to this script (from the BASH script) contains DISCONNECTED
     print ( "we are disconnected\r\n" ) ;
break;

为了避免错误,了解 switch 语句是如何执行的很重要。switch 语句逐行执行(实际上是逐语句执行)。一开始,没有代码被执行。只有找到一个 case 语句,其表达式的计算结果与 switch 表达式的值匹配时,PHP 才会开始执行这些语句。PHP 继续执行语句,直到 switch 块结束,或者它第一次看到 break 语句。如果你不在一个 case 语句列表的末尾写一个 break 语句,PHP 将继续执行下一个 case 的语句。

https://www.php.net/manual/en/control-structures.switch.php


推荐阅读