Bash到php regexp

时间:2019-06-19 15:25:38

标签: php regex bash

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

这是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"

1 个答案:

答案 0 :(得分:2)

每个case都需要一个break来阻止其运行,而不是{}

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语句。如果您没有在案例陈述列表的末尾编写break语句,PHP将继续执行以下案例的陈述。

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