Warning: stripos() expects at least 2 parameters in php - 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";
}

Related

How to convert object class into string

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).

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.

Check if any value in an array exists within a haystack string

I have a string like abcdefg123hijklm. I also have an array which contains several strings like [456, 123, 789].
I want to check if the number in the middle of abcdefg123hijklm exists in the array.
How can I do that? I guess in_array() won't work.
So you want to check if any substring of that particular string (lets call it $searchstring) is in the array?
If so you will need to iterate over the array and check for the substring:
foreach($array as $string)
{
if(strpos($searchstring, $string) !== false)
{
echo 'yes its in here';
break;
}
}
See: http://php.net/manual/en/function.strpos.php
If you want to check if a particular part of the String is in the array you will need to use substr() to separate that part of the string and then use in_array() to find it.
http://php.net/manual/en/function.substr.php
Another option would be to use regular expressions and implode, like so:
if (preg_match('/'.implode('|', $array).'/', $searchstring, $matches))
echo("Yes, the string '{$matches[0]}' was found in the search string.");
else
echo("None of the strings in the array were found in the search string.");
It's a bit less code, and I would expect it to be more efficient for large search strings or arrays, since the search string will only have to be parsed once, rather than once for every element of the array. (Although you do add the overhead of the implode.)
The one downside is that it doesn't return the array index of the matching string, so the loop might be a better option if you need that. However, you could also find it with the code above followed by
$match_index = array_search($matches[0], $array);
Edit: Note that this assumes you know your strings aren't going to contain regular expression special characters. For purely alphanumeric strings like your examples that will be true, but if you're going to have more complex strings you would have to escape them first. In that case the other solution using a loop would probably be simpler.
You can do it reversely. Assume your string is $string and array is $array.
foreach ($array as $value)
{
// strpos can return 0 as a first matched position, 0 == false but !== false
if (strpos($string, $value) !== false)
{
echo 'Matched value is ' . $value;
}
}
Use this to get your numbers
$re = "/(\d+)/";
$str = "abcdefg123hijklm";
preg_match($re, $str, $matches);
and ( 123 can be $matches[1] from above ):
preg_grep('/123/', $array);
http://www.php.net/manual/en/function.preg-grep.php

filter specific string in php

$var="UseCountry=1
UseCountryDefault=1
UseState=1
UseStateDefault=1
UseLocality=1
UseLocalityDefault=1
cantidad_productos=5
expireDays=5
apikey=ABQIAAAAFHktBEXrHnX108wOdzd3aBTupK1kJuoJNBHuh0laPBvYXhjzZxR0qkeXcGC_0Dxf4UMhkR7ZNb04dQ
distancia=15
AutoCoord=1
user_add_locality=0
SaveContactForm=0
ShowVoteRating=0
Listlayout=0
WidthThumbs=100
HeightThumbs=75
WidthImage=640
HeightImage=480
ShowImagesSystem=1
ShowOrderBy=0
ShowOrderByDefault=0
ShowOrderDefault=DESC
SimbolPrice=$
PositionPrice=0
FormatPrice=0
ShowLogoAgent=1
ShowReferenceInList=1
ShowCategoryInList=1
ShowTypeInList=1
ShowAddressInList=1
ShowContactLink=1
ShowMapLink=1
ShowAddShortListLink=1
ShowViewPropertiesAgentLink=1
ThumbsInAccordion=5
WidthThumbsAccordion=100
HeightThumbsAccordion=75
ShowFeaturesInList=1
ShowAllParentCategory=0
AmountPanel=
AmountForRegistered=5
RegisteredAutoPublish=1
AmountForAuthor=5
AmountForEditor=5
AmountForPublisher=5
AmountForManager=5
AmountForAdministrator=5
AutoPublish=1
MailAdminPublish=1
DetailLayout=0
ActivarTabs=0
ActivarDescripcion=1
ActivarDetails=1
ActivarVideo=1
ActivarPanoramica=1
ActivarContactar=1
ContactMailFormat=1
ActivarReservas=1
ActivarMapa=1
ShowImagesSystemDetail=1
WidthThumbsDetail=120
HeightThumbsDetail=90
idCountryDefault=1
idStateDefault=1
ms_country=1
ms_state=1
ms_locality=1
ms_category=1
ms_Subcategory=1
ms_type=1
ms_price=1
ms_bedrooms=1
ms_bathrooms=1
ms_parking=1
ShowTextSearch=1
minprice=
maxprice=
ms_catradius=1
idcatradius1=
idcatradius2=
ShowTotalResult=1
md_country=1
md_state=1
md_locality=1
md_category=1
md_type=1
showComments=0
useComment2=0
useComment3=0
useComment4=0
useComment5=0
AmountMonthsCalendar=3
StartYearCalendar=2009
StartMonthCalendar=1
PeriodOnlyWeeks=0
PeriodAmount=3
PeriodStartDay=1
apikey=ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
";
in that string only i want "api==ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ";
plz guide me correctly;
EDIT
As shamittomar pointed out, the parse_str will not work for this situation, posted the proper regex below.
Given this seems to be a QUERY STRING, use the parse_str() function PHP provides.
UPDATE
If you want to do it with regex using preg_match() as powertieke pointed out:
preg_match('/apikey=(.*)/', $var, $matches);
echo $matches[1];
Should do the trick.
preg_match(); should be right up your alley
people are so fast to jump to preg match when this can be done with regular string functions thats faster.
$string = '
expireDays=5
apikey=ABQIAAAAFHktBEXrHnX108wOdzd3aBTupK1kJuoJNBHuh0laPBvYXhjzZxR0qkeXcGC_0Dxf4UMhkR7ZNb04dQ
distancia=15
AutoCoord=1';
//test to see what type of line break it is and explode by that.
$parts = (strstr($string,"\r\n") ? explode("\r\n",$string) : explode("\n",$string));
$data = array();
foreach($parts as $part)
{
$sub = explode("=",trim($part));
if(!empty($sub[0]) || !empty($sub[1]))
{
$data[$sub[0]] = $sub[1];
}
}
and use $data['apikey'] for your api key, i would also advise you to wrpa in function.
I can bet this is a better way to parse the string and much faster.
function ParsemyString($string)
{
$parts = (strstr($string,"\r\n") ? explode("\r\n",$string) : explode("\n",$string));
$data = array();
foreach($parts as $part)
{
$sub = explode("=",trim($part));
if(!empty($sub[0]) || !empty($sub[1]))
{
$data[$sub[0]] = $sub[1];
}
}
return $data;
}
$data = ParsemyString($string);
First of all, you are not looking for
api==ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
but you are looking for
apikey=ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
It is important to know if the api-key property always occurs at the end and if the length of the api-key value is always the same. I this is the case you could use the PHP substr() function which would be easiest.
If not you would most probably need a regular expression which you can feed to PHPs preg_match() function. Something along the lines of apikey==[a-zA-Z0-9\-] Which matches an api-key containing a-z in both lowercase and uppercase and also allows for dashes in the key. If you are using the preg_match() function you can retrieve the matches (and thus your api-key value).

stristr Case-insensitive search PHP

Please excuse my noob-iness!
I have a $string, and would like to see if it contains any one or more of a group of words, words link ct, fu, sl** ETC. So I was thinking I could do:
if(stristr("$input", "dirtyword1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
elseif(stristr("$input", "dirtyWord1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord2");
}
...ETC. BUT, I don't want to have to keep doing if/elseif/elseif/elseif/elseif...
Can't I just do a switch statement OR have an array, and then simply say something like?:
$dirtywords = { "f***", "c***", w****", "bit**" };
if(stristr("$input", "$dirtywords"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
I'd appreciate any help at all
Thank you
$dirty = array("fuc...", "pis..", "suc..");
$censored = array("f***", "p***", "s***");
$input= str_ireplace($dirty, $censored , $input);
Note, that you don't have to check stristr() to do a str_ireplace()
http://php.net/manual/en/function.str-ireplace.php
If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do 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.
Surely not the best solution since I don't know too much PHP, but what about a loop ?
foreach (array("word1", "word2") as $word)
{
if(stristr("$input", $word))
{
$input = str_ireplace("$input", $word" "thisWillReplaceDirtyWord");
}
}
When you have several objects to test, think "loop" ;-)

Categories