-1

如何将以下对象转换为字符串:

$ssh->exec('tail -1 /var/log/playlog.csv');

所以我可以将字符串解析为 strripos() 中的第一个参数:

if($idx = strripos($ssh,','))//Get the last index of ',' substring 
{
$ErrorCode = substr($ssh,$idx + 1,(strlen($ssh) - $idx) - 1); //using the found index, get the error code using substring
echo " " .$Playlist.ReturnError($ErrorCode); //The ReturnError function just replaces the error code with a custom error
}

目前,当我运行我的脚本时,我收到以下错误消息:

strpos() expects parameter 1 to be string

我见过类似的问题,包括stdClass 类的一个 Object could not be convert to string,但是我似乎仍然无法提出解决方案。

4

1 回答 1

0

这行代码有两个问题:

if($idx = strripos($ssh,','))
  1. $ssh是某个类的一个实例。你在上面使用它作为$ssh->exec(...). 您应该检查它返回的值(可能是一个字符串)strripos(),而不是 on $ssh

  2. strripos()FALSE如果它在找到它时找不到子字符串或数字(可以是),则返回0。但在布尔上下文中,0false. 这意味着此代码无法区分逗号 ( ,) 是作为字符串的第一个字符还是根本没有找到的情况。

假设$ssh->exec()将远程命令的输出作为字符串返回,那么编写此代码的正确方法是:

$output = $ssh->exec('tail -1 /var/log/playlog.csv');

$idx = strrpos($output, ',');        //Get the last index of ',' substring 
if ($idx !== FALSE) {
    // The value after the last comma is the error code
    $ErrorCode = substr($output, $idx + 1);
    echo ' ', $Playlist, ReturnError($ErrorCode);
} else {
   // Do something else when it doesn't contain a comma
}

没有必要使用strripos(). 它执行不区分大小写的比较,但您正在搜索不是字母的字符,因此区分大小写对它没有任何意义。

您可以改用strrpos()它,它会产生相同的结果,并且比strripos().


另一种方法

获得相同结果的另一种方法是使用explode()分成$output几部分(用逗号分隔)并获取最后一块(使用end()or array_pop())作为错误代码:

$output = $ssh->exec('tail -1 /var/log/playlog.csv');

$pieces = explode(',', $output);
if (count($pieces) > 1) {
    $ErrorCode = (int)end($pieces);
    echo ' ', $Playlist, ReturnError($ErrorCode);
} else {
   // Do something else when it doesn't contain a comma
}

这不一定是更好的方法。然而,它对 PHP(使用strrpos()并且substr()更类似于 C 代码的代码)更具可读性和惯用性。

于 2018-04-03T09:31:59.020 回答