Error using substr() - php

I am getting error while using substr:
Warning: substr() expects parameter 3 to be long
I am new to php and could not locate the problem. I would appreciate any help.
Here is the code:
function prepare_string($passed_string,$length)
{
$matches = array("`","!","#","®","©","~","#","$","%","^","&","*","-","=","+","|","\\","[","{","]","}","(",")",";",":","\"","'",",","<",">",".","?","/","\'","\\","'","’");
$passed_string =substr($passed_string,0,$length);
for($i=0;$i<count($matches);$i++)
{
$passed_string = str_replace($matches[$i],"_",$passed_string);
}
$passed_string = str_replace(" ","_",$passed_string);
return $passed_string;
}

var_dump($length) and see what's in there.
remove foreach loop and instead put just this line $passed_string = str_replace($matches,"_",$passed_string);
add " " in $matches array too and then you can get rid of this line $passed_string = str_replace(" ","_",$passed_string);

Sounds like substr() is not receiving a well-formed value for some reason... One option would be to add a line inside the function that casts $length as an integer. Example:
function prepare_string($passed_string,$length)
{
// Add this line
$length = (int) $length;
$matches = array("`","!","#","®","©","~","#","$","%","^","&","*","-","=","+","|","\\","[","{","]","}","(",")",";",":","\"","'",",","<",">",".","?","/","\'","\\","'","’");
$passed_string =substr($passed_string,0,$length);
for($i=0;$i<count($matches);$i++)
{
$passed_string = str_replace($matches[$i],"_",$passed_string);
}
$passed_string = str_replace(" ","_",$passed_string);
return $passed_string;
}

Related

Creating a function that takes arguments and passes variables

I am creating a script that will locate a field in a text file and get the value that I need.
First used the file() function to load my txt into an array by line.
Then I use explode() to create an array for the strings on a selected line.
I assign labels to the array's to describe a $Key and a $Value.
$line = file($myFile);
$arg = 3
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
This works fine but that is a lot of code to have to do over and over again for everything I want to get out of the txt file. So I wanted to create a function that I could call with an argument that would return the value of $key and $val. And this is where I am failing:
<?php
/**
* #author Jason Moore
* #copyright 2014
*/
global $line;
$key = '';
$val = '';
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$arg = 3;
$Character_Name = 3
function get_plr_data2($arg){
global $key;
global $val;
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return;
}
get_plr_data2($Character_Name);
echo "This character's ",$key,' is ',$val;
?>
I thought that I covered the scope with setting the values in the main and then setting them a global within the function. I feel like I am close but I am just missing something.
I feel like there should be something like return $key,$val; but that doesn't work. I could return an Array but then I would end up typing just as much code to the the info out of the array.
I am missing something with the function and the function argument to. I would like to pass and argument example : get_plr_data2($Character_Name); the argument identifies the line that we are getting the data from.
Any help with this would be more than appreciated.
::Updated::
Thanks to the answers I got past passing the Array.
But my problem is depending on the arguments I put in get_plr_data2($arg) the number of values differ.
I figured that I could just set the Max of num values I could get but this doesn't work at all of course because I end up with undefined offsets instead.
$a = $cdata[0];$b = $cdata[1];$c = $cdata[2];
$d = $cdata[3];$e = $cdata[4];$f = $cdata[5];
$g = $cdata[6];$h = $cdata[7];$i = $cdata[8];
$j = $cdata[9];$k = $cdata[10];$l = $cdata[11];
return array($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l);
Now I am thinking that I can use the count function myCount = count($c); to either amend or add more values creating the offsets I need. Or a better option is if there was a way I could generate the return array(), so that it would could the number of values given for array and return all the values needed. I think that maybe I am just making this a whole lot more difficult than it is.
Thanks again for all the help and suggestions
function get_plr_data2($arg){
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return array($key,$val);
}
Using:
list($key,$val) = get_plr_data2(SOME_ARG);
you can do this in 2 way
you can return both values in an array
function get_plr_data2($arg){
/* do what you have to do */
$output=array();
$output['key'] =$key;
$output['value']= $value;
return $output;
}
and use the array in your main function
you can use reference so that you can return multiple values
function get_plr_data2($arg,&$key,&$val){
/* do job */
}
//use the function as
$key='';
$val='';
get_plr_data2($arg,$key,$val);
what ever you do to $key in function it will affect the main functions $key
I was over thinking it. Thanks for all they help guys. this is what I finally came up with thanks to your guidance:
<?php
$ch_file = "Thor";
$ch_name = 3;
$ch_lvl = 4;
$ch_clss = 15;
list($a,$b)= get_char($ch_file,$ch_name);//
Echo $a,': ',$b; // Out Puts values from the $cdata array.
function get_char($file,$data){
$myFile = $file.".txt";
$line = file($myFile);
$cdata = preg_split('/\s+/', trim($line[$data]));
return $cdata;
}
Brand new to this community, thanks for all the patience.

get string piece, before last needle

Given
$str = "asd/fgh/jkl/123
If we want to get string piece after last slash , we can use function strrchr() right?
In php not function, to get string piece, before last slah, that is asd/fgh/jkl ?
I know this can make via regex or other way, I am asking about internal function?
You can use
$str = "asd/fgh/jkl/123";
echo substr($str, 0,strrpos($str, '/'));
Output
asd/fgh/jkl
$str = "asd/fgh/jkl/123";
$lastPiece = end(explode("/", $str));
echo $lastPiece;
output: 123;
explode() converts the string into an array using "/" as a separator (you can pick the separator)
end() returns the last item of the array
You can do this by:
explode — Split a string by string (Documentation)
$pieces = explode("/", $str );
example
$str = "asd/fgh/jkl/123";
$pieces = explode("/", $str );
print_r($pieces);
$count= count($pieces);
echo $pieces[$count-1]; //or
echo end($pieces);
Codepad
Use this powerful custom function
/* $position = false and $sub = false show result of before first occurance of $needle */
/* $position = true and $sub false show result of before last occurance of $needle */
/* $position = false and $sub = true show result of after first occurance of $needle */
/* $position = true and $sub true show result of after last occurance of $needle */
function CustomStrStr($str,$needle,$position = false,$sub = false)
{
$Isneedle = strpos($str,$needle);
if ($Isneedle === false)
return false;
$needlePos =0;
$return;
if ( $position === false )
$needlePos = strpos($str,$needle);
else
$needlePos = strrpos($str,$needle);
if ($sub === false)
$return = substr($str,0,$needlePos);
else
$return = substr($str,$needlePos+strlen($needle));
return $return;
}

PHP : foreach warning

I'am executing code :
<?php
$input="ABC123";
$splits = chunk_split($input,2,"");
foreach($splits as $split)
{
$split = strrev($split);
$input = $input . $split;
}
?>
And output that i want is :
BA1C32
But it gaves me Warning.
Warning: Invalid argument supplied for foreach() in /home/WOOOOOOOOHOOOOOOOO/domains/badhamburgers.com/public_html/index.php on line 4
chunk_split doesn't return an array but rather a part of the string.
You should use str_split instead:
$input="ABC123";
$splits = str_split($input, 2);
And don't forget to reset your $input before the loop, else it will contain the old data aswell.
It looks like http://php.net/manual/en/function.chunk-split.php returns a string, not an array. You could use str_split instead:
$input = "ABC123";
$splits = str_split( $input, 2 );
$output = "";
foreach( $splits as $split ){
$split = strrev($split);
$output .= $split;
}
As the documentation for chunk_split mentions clearly, http://php.net/manual/en/function.chunk-split.php chunk split returns a string.
foreach expects an array as first argument.

Warning: strpos() [function.strpos]: Empty delimiter

I have a plugin that uses strpos() method and on one site I'm getting this error
Warning: strpos() [function.strpos]: Empty delimiter. in /home/mysite/public_html/wp-includes/compat.php on line 55
Any ideas what the likely cause of this could be?
excerpt from compat.php
if (!function_exists('stripos')) {
function stripos($haystack, $needle, $offset = 0) {
return strpos(strtolower($haystack), strtolower($needle), $offset);
}
}
My code...
function myFunction($thePost)
{
$theContent = $thePost->post_content;
$myVar1 = array();
preg_match_all('/<a\s[^>]*href=\"([^\"]*)\"[^>]*>(.*)<\/a>/siU',$theContent,$myVar1);
$myVar2 = 0;
foreach ($myVar1[1] as $myVar3)
{
$myVar4 = $myVar1[2][$myVar2];
$myVar5 = FALSE;
$myVar6 = get_bloginfo('wpurl');
$myVar7 = str_replace('http://www.','',$myVar3);
$myVar7 = str_replace('http://','',$myVar7);
$myVar8 = str_replace('http://www.','',$myVar6);
$myVar8 = str_replace('http://','',$myVar8);
if (strpos($myVar3,'http://')!==0 || strpos($myVar7,$myVar8)===0) return TRUE;
$myVar2++;
}
return FALSE;
}
Something is passing an empty string as the second argument to Wordpress' implementation of stripos() (and it's not the code you've pasted above).
Can I ask why you a using PHP 4?
TRY ADDING double quotes on the on the variable
change this line:
if (strpos($myVar3,'http://')!==0 || strpos($myVar7,$myVar8)===0) return TRUE;
into:
if (strpos(".$myVar3.",'http://')!==0 || strpos(".$myVar7.",".$myVar8.")===0) return TRUE;

Parsing a string in PHP

My string is like the following format:
$string =
"name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
I want to split the string like the following:
$str[0] = "name=xxx&id=11";
$str[1] = "name=yyy&id=12";
$str[2] = "name=zzz&id=13";
$str[3] = "name=aaa&id=10";
how can I do this in PHP ?
Try this:
$matches = array();
preg_match_all("/(name=[a-zA-Z0-9%_-]+&id=[0-9]+)/",$string,$matches);
$matches is now an array with the strings you wanted.
Update
function get_keys_and_values($string /* i.e. name=yyy&id=10 */) {
$return = array();
$key_values = split("&",$string);
foreach ($key_values as $key_value) {
$kv_split = split("=",$key_value);
$return[$kv_split[0]] = urldecode($kv_split[1]);
}
return $return;
}
$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
$arr = split("name=", $string);
$strings = aray();
for($i = 1; $i < count($arr), $i++){
$strings[$i-1] = "name=".substr($arr[$i],0,-1);
}
The results will be in $strings
I will suggest using much simpler term
Here is an example
$string = "name=xxx&id=11;name=yyy&id=12;name=zzz&id=13;name=aaa&id=10";
$arr = explode(";",$string); //here is your array
If you want to do what you asked, nothing more or less , that's explode('&', $string).
If you have botched up your example and you have a HTTP query string then you want to look at parse_str().

Categories