【问题标题】:seperating numberic strings from words in php在php中将数字字符串与单词分开
【发布时间】:2017-11-01 23:51:34
【问题描述】:

我有一个在我的 Windows 机器上运行 cmd 命令的 php 脚本,我将我的标准输出从命令 shell 重定向回我的 php 脚本,我得到以下结果:

接口统计接收发送字节数 30750280 8480324

单播数据包 44928 43160

非单播数据包 0 0

丢弃 0 0

错误 0 0

未知协议 0

我想要做的是使用 RegEx 来格式化结果,以便我可以以表格形式输出数据,例如:

    interface statistics
received| 3535353535
sent    | 4664646646
errors  | 0

按这个顺序。

到目前为止,我只是尝试使用下面的代码仅格式化包含“字节”的行,但运气不佳;

if (preg_match('/Bytes/',$lines)) {
 $lines = trim($lines);
 $pieces = preg_split("/[\s,]+/", $lines);
echo $lines;
echo "Sent: ".(int)$pieces[1]."Reeived: ".$pieces[2];

    preg_match_all('/(\d)|(\w)/', $lines, $matches);

    $numbers = implode($matches[1]);
    $letters = implode($matches[2]);

//var_dump($numbers, $letters);
//echo $numbers;
//echo  $letters."letters";

}

【问题讨论】:

标签: php html regex


【解决方案1】:

代码:(PHP Demo) (Pattern Demo)

$shell_output='Interface Statistics Received Sent Bytes 30750280 8480324

Unicast packets 44928 43160

Non-unicast packets 0 0

Discards 0 0

Errors 0 0

Unknown protocols 0';

$pattern='/Interface Statistics Received Sent Bytes (\d+) (\d+).*Errors (\d+).*/s';
$replace="interface statistics\nreceived| $1\nsent\t| $2\nerrors\t| $3";
echo preg_replace($pattern,$replace,$shell_output);

输出:

interface statistics
received| 30750280
sent    | 8480324
errors  | 0

该模式在Interface Statistics Received Sent Bytes 上使用文字匹配来减少步数。模式末尾的 s 修饰符/标志将允许 .(点 = 任何字符)匹配换行符。该模式旨在用新的替换文本替换整个文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多