How to convert object class into string - php

How can I convert the following object into string:
$ssh->exec('tail -1 /var/log/playlog.csv');
So I can parse the string as the first parameter in 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
}
As currently when I run my script I get the following error message:
strpos() expects parameter 1 to be string
I've seen similar questions including this one Object of class stdClass could not be converted to string , however I still can't seem to come up with a solution.

There are two problems with this line of code:
if($idx = strripos($ssh,','))
$ssh is an instance of some class. You use it above as $ssh->exec(...). You should check the value it returns (probably a string) and strripos() on it, not on $ssh.
strripos() returns FALSE if it cannot find the substring or a number (that can be 0) when it founds it. But in boolean context, 0 is the same as false. This means this code cannot tell apart the cases when the comma (,) is found as the first character of the string or it is not found at all.
Assuming $ssh->exec() returns the output of the remote command as string, the correct way to write this code is:
$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
}
There is no need to use strripos(). It performs case-insensitive comparison but you are searching for a character that is not a letter, consequently the case-sensitivity doesn't make any sense for it.
You can use strrpos() instead, it produces the same result and it's a little bit faster than strripos().
An alternative way
An alternative way to get the same outcome is to use explode() to split $output in pieces (separated by comma) and get the last piece (using end() or array_pop()) as the error code:
$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
}
This is not necessarily a better way to do it. It is, however, more readable and more idiomatic to PHP (the code that uses strrpos() and substr() resembles more the C code).

Related

Warning: stripos() expects at least 2 parameters in php

I wrote a simple function in php and passing arguments to uppercase the letters based on passing array index value but I'm getting this error
Warning: stripos() expects at least 2 parameters
what I'm doing wrong can anyone suggest me.
i'm newbie to php just starts learning.
<?php
function doCapital($string, $array)
{
$stringArray = explode(",", $string);
for( $i=0; $i<count($stringArray); $i++)
{
if(stripos($stringArray)>-1){
$stringArray[$i] = $stringArray[$i].ucfirst();
echo $stringArray[$i];
}
}
return implode(" ",$stringArray);
}
echo doCapital('abcd', [1,2]);
Apologies, on re-reading my last answer I realise that it did seem very unfriendly - I bashed out a quick answer and didn't read it back. What I was trying to say is that with errors like this the quickest solutions to go to the php manual and check the required parameters - which in this case is a needle and a haystack (i.e something to search, and something to search in).
You will likely find the same error here
$stringArray[$i] = $stringArray[$i].ucfirst(); as ucfirst requires a string to be passed - here you're using it like jQuery so php thinks you are trying to concatenate a string, it should say ucfirst($stringArray[$i])
you also can't explode with a comma unless your string contains them, so in the example you have you would receive the same string back, I think you mean to use something like str_split
also I would reiterate that I think you need to use in_array for what you're trying to achieve, like this:
function doCapital($string, $array)
{
$stringArray = str_split($string);
foreach($stringArray as $key => $value)
{
//see if the key exists in the array of characters to change the case for
//and update if it does
if(in_array($key,$array)){
$stringArray[$key] = ucfirst($value);//thinking about it I might just use strtoupper since there's only one letter anyway - I'm not sure that there's any real performance benefit either way
}
}
return implode("",$stringArray);
}
echo doCapital('abcd', [1,2]); //outputs aBCd
stripos - Find the position of the first occurrence of a case-insensitive substring in a string
You are missing the second parameter, The correct syntax to use the function stripos is
stripos ($haystack ,$needle);
Here
$haystack -> The string in which you are searching
$needle -> The substring
For example :
$findme = 'x';
$mystring1 = 'xyz';
$pos1 = stripos($mystring1, $findme);
if ($pos1 !== false) {
echo "We found '$findme' in '$mystring1' at position $pos1";
}

Array and substring php

//array data
{
$results[] = $result;
$SiteID=$result["site_id"];
$pay_sale_id=$result["pay_sale_id"];
$pay_payment_info=$result["pay_payment_info"];
$payNo= substring_index(substring_index('$result["pay_payment_info"]', '$USER=', -1), '~$TAGROLE', 1);
}
The content of pay_payment_info is as follows
#$TAG=6F0000173~$USER=james~$TAGROLE=0
I want to extract only the user info, but i get error:
Fatal error: Call to undefined function substring_index() in line
Considering the user info always begins with ~$USER= and ends with a ~ we can get the result using simple regex:
preg_match('/\~\$USER=(?<user>[^~]+)/', $pay_payment_info, $match);
var_dump($match['user']);
As previous comments said - there is no such function like substring_index in core PHP
This question is possible duplicate of following Php get string between tags
topic
Here is working example with usage of strpos http://php.net/manual/pl/function.strpos.php
and substr http://php.net/manual/pl/function.substr.php
$var = '$TAG=6F0000173~$USER=james~$TAGROLE=0';
$m = substr($var, strpos($var, '~$USER=')+7);
var_dump($m); //returns string(16) "james~$TAGROLE=0"
$m = substr($m, 0, strpos($m, '~$'));
var_dump($m); //returns string(5) "james"
it seems that the problem is you have no substring_index() function or method, yet you attempt to invoke it twice.
I am not sure why you use the ~ as a delimiter but that should be ok, although using a , would have resulted in less work; each of the attributes of your querystring would have been able to be addressed directly then.
what you want to do is use the php version of split() which is explode() here is a link to the manual.
what you want to do is split the inc string:
$aUserInfo = explode('~', $result['pay_payment_info']);
now you have an array. loop through it and make it like you want:
$result = array();
foreach($aUserInfo as $v){
$aTmp = explode('=',$v);
$result[$aTmp[0]] = $aTmp[1];
}
at the end of this you have an array with keys as keys and their respective values as values, i.e.
$result = array( 'tag' => '6F0000173',
'user'=> 'James',
'tagrole'=> 0 );
The error tells you exactly why it is an error: substring_index is not a valid/native PHP function... you can define your own function of substring_index, though.
However, given the string:
$TAG=6F0000173~$USER=james~$TAGROLE=0
to get the $USER=james part, you can use explode as follows--
$payNo = explode("~", $result["pay_payment_info"])
Now, you have the $USER info in $payNo[1]
If you want to go even further and just get the value of what $USER value is, then you can use PHP's native substr function:
$justUserPart = substr($payNo[1], strpos($payNo[1], "=")+1);
echo $justUserPart;
Please Note: The above assumes that you will always have the string in the format of
$TAG=...~$USER=...~$TAGROLE=...

Unable to make use of PHP regex matches

I have some PHP code that accepts an uploaded file from an HTML form then reads through it using regex to look for specific lines (in the case below, those with "Number" followed by an integer).
The regex matches the integers like I want it to, but of course they're returned as strings in $matches. I need to check if the integer is between 0 and 9 but I um unable to do this no matter what I try.
Using intval() or (int) to first convert the matches to integers always returns 0 even though the given string contains only integers. And using in_array to compare the integer to an array of 0-9 as strings always returns false as well for some reason. Here's the trouble code...
$myFile = file($myFileTmp, FILE_IGNORE_NEW_LINES);
$numLines = count($myFile) - 1;
$matches = array();
$nums = array('0','1','2','3','4','5','6','7','8','9');
for ($i=0; $i < $numLines; $i++) {
$line = trim($myFile[$i]);
$numberMatch = preg_match('/Number(.*)/', $line, $matches);
if ($numberMatch == 1 and ctype_space($matches[1]) == False) { // works up to here
$number = trim($matches[1]); // string containing an integer only
echo(intval($number)); // conversion doesn't work - returns 0 regardless
if (in_array($number,$nums)) { // searching in array doesn't work - returns FALSE regardless
$number = "0" . $number;
}
}
}
I've tried type checking, double quotes, single quotes, trimming whitespace, UTF8 encoding...what else could it possibly be? I'm about to give up on this app entirely, please save me.
Use '===' for eq for example
if 1 == '1' then true;
if 1 === '1' false;
if 1 == true then true;
if 1 === true then false
You can show file?
You write in your question that you're using a regular expression to look for the term "Number" followed by a single digit (0-9).
A regular expression for it would be:
/Number(\d)/
It will contain in the matching group 1 the number (digit) you're looking for.
The pattern you use:
/Number(.*)/
can contain anything (but a line-break) in the first matching group. It obviously is matching too much. You then have a problem filtering that too much retro-actively.
It normally works best to first look as precise as possible than to fiddle with too much noise afterwards.

Obtaining PHP regex matches but unable to do anything with them

I have some PHP code that accepts an uploaded file from an HTML form then reads through it using regex to look for specific lines (in the case below, those with "Track Number" followed by an integer).
The file is an XML file that looks like this normally...
<key>Disc Number</key><integer>2</integer>
<key>Disc Count</key><integer>2</integer>
<key>Track Number</key><integer>1</integer>
But when PHP reads it in it gets rid of the XML tags for some reason, leaving me with just...
Disc Number2
Disc Count2
Track Number1
The file has to be XML, and I don't want to use SimpleXML cause that's a whole other headache. The regex matches the integers like I want it to (I can print them out "0","1","2"...) but of course they're returned as strings in $matches, and it seems I'm unable to make use of these strings. I need to check if the integer is between 0 and 9 but I um unable to do this no matter what I try.
Using intval() or (int) to first convert the matches to integers always returns 0 even though the given string contains only integers. And using in_array to compare the integer to an array of 0-9 as strings always returns false as well for some reason. Here's the trouble code...
$myFile = file($myFileTmp, FILE_IGNORE_NEW_LINES);
$numLines = count($myFile) - 1;
$matches = array();
$nums = array('0','1','2','3','4','5','6','7','8','9');
for ($i=0; $i < $numLines; $i++) {
$line = trim($myFile[$i]);
$numberMatch = preg_match('/Track Number(.*)/', $line, $matches); // if I try matching integers specifically it doesn't return a match at all, only if I do it like this - it gives me the track number I want but I can't do anything with it
if ($numberMatch == 1 and ctype_space($matches[1]) == False) {
$number = trim($matches[1]); // string containing an integer only
echo(intval($number)); // conversion doesn't work - returns 0 regardless
if (in_array($number,$nums)===True) { // searching in array doesn't work - returns FALSE regardless
$number = "0" . $number;
}
}
}
I've tried type checking, double quotes, single quotes, trimming whitespace, UTF8 encoding, === operator, regex matching numbers specifically with (\d+) (which doesn't return a match at all)...what else could it possibly be? When I try these things with regular strings it works fine, but the regex is messing everything up here. I'm about to give up on this app entirely, please save me.
Why is SimpleXML not an option? Consider the following code:
$str = "<container><key>Disc Number</key><integer>2</integer>
<key>Disc Count</key><integer>2</integer>
<key>Track Number</key><integer>1</integer></container>";
$xml = simplexml_load_string($str);
foreach ($xml->key as $k) {
// do sth. here with it
}
You should read RegEx match open tags except XHTML self-contained tags -- while doesn't exactly match your use case it has good reasons why one should use something besides straight up regexp matching for your use case.
Assuming that files only contain a single Track Number you can simplify what you're doing a lot. See the following:
test.xml
<key>Disc Number</key><integer>2</integer>
<key>Disc Count</key><integer>2</integer>
<key>Track Number</key><integer>1</integer>
test.php
<?php
$contents = file_get_contents('test.xml');
$result = preg_match_all("/<key>Track Number<\/key><integer>(\d)<\/integer>/", $contents, $matches);
if ($result > 0) {
print_r($matches);
$trackNumber = (int) $matches[1][0];
print gettype($trackNumber) . " - " . $trackNumber;
}
Result
$ php -f test.php
Array
(
[0] => Array
(
[0] => <key>Track Number</key><integer>1</integer>
)
[1] => Array
(
[0] => 1
)
)
integer - 1%
As you can see, there is no need to iterate through the files line by line when using preg_match_all. The matching here is very specific so you don't have to do extra checks for whitespace or validate that it's a number. Which you're doing against a string value currently.

very large php string magically turns into array

I am getting an "Array to string conversion error on PHP";
I am using the "variable" (that should be a string) as the third parameter to str_replace. So in summary (very simplified version of whats going on):
$str = "very long string";
str_replace("tag", $some_other_array, $str);
$str is throwing the error, and I have been trying to fix it all day, the thing I have tried is:
if(is_array($str)) die("its somehow an array");
serialize($str); //inserted this before str_replace call.
I have spent all day on it, and no its not something stupid like variables around the wrong way - it is something bizarre. I have even dumped it to a file and its a string.
My hypothesis:
The string is too long and php can't deal with it, turns into an array.
The $str value in this case is nested and called recursively, the general flow could be explained like this:
--code
//pass by reference
function the_function ($something, &$OFFENDING_VAR, $something_else) {
while(preg_match($something, $OFFENDING_VAR)) {
$OFFENDING_VAR = str_replace($x, y, $OFFENDING_VAR); // this is the error
}
}
So it may be something strange due to str_replace, but that would mean that at some point str_replace would have to return an array.
Please help me work this out, its very confusing and I have wasted a day on it.
---- ORIGINAL FUNCTION CODE -----
//This function gets called with multiple different "Target Variables" Target is the subject
//line, from and body of the email filled with << tags >> so the str_replace function knows
//where to replace them
function perform_replacements($replacements, &$target, $clean = TRUE,
$start_tag = '<<', $end_tag = '>>', $max_substitutions = 5) {
# Construct separate tag and replacement value arrays for use in the substitution loop.
$tags = array();
$replacement_values = array();
foreach ($replacements as $tag_text => $replacement_value) {
$tags[] = $start_tag . $tag_text . $end_tag;
$replacement_values[] = $replacement_value;
}
# TODO: this badly needs refactoring
# TODO: auto upgrade <<foo>> to <<foo_html>> if foo_html exists and acting on html template
# Construct a regular expression for use in scanning for tags.
$tag_match = '/' . preg_quote($start_tag) . '\w+' . preg_quote($end_tag) . '/';
# Perform the substitution until all valid tags are replaced, or the maximum substitutions
# limit is reached.
$substitution_count = 0;
while (preg_match ($tag_match, $target) && ($substitution_count++ < $max_substitutions)) {
$target = serialize($target);
$temp = str_replace($tags,
$replacement_values,
$target); //This is the line that is failing.
unset($target);
$target = $temp;
}
if ($clean) {
# Clean up any unused search values.
$target = preg_replace($tag_match, '', $target);
}
}
How do you know $str is the problem and not $some_other_array?
From the manual:
If search and replace are arrays, then str_replace() takes a value
from each array and uses them to search and replace on subject. If
replace has fewer values than search, then an empty string is used for
the rest of replacement values. If search is an array and replace is a
string, then this replacement string is used for every value of
search. The converse would not make sense, though.
The second parameter can only be an array if the first one is as well.

Categories