PHP Implode with breakpoints - php

Is there a way to implode with breakpoints
$a1 = array('a1','a2','a3','a4');
implode("<br/>",$a1);
I am expecting the output something like this
a1<br/>
a2<br/>
a3<br/>
a4<br/>
I am getting Warning: implode() [function.implode]: Invalid arguments passed

This produces exactly the result you want to:
$a1 = array('a1','a2','a3','a4');
$result=implode("<br/>\n",$a1)."<br/>";
echo $result;
/**
a1<br/>
a2<br/>
a3<br/>
a4<br/>
*/
working demo : http://3v4l.org/PWVTb
Implode by using the string "<br/>" plus the new line character \n. Also adding a "<br/>" string at the end.
Thats how i understood your question, if i misunderstood let me know. Anyway, the result is exactly what you asked.

Related

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

How to make str_replace work in printf?

I am trying to replace the underscore character in printf. But it might be missing something because it does not work. Does anyone know how to fix this?
printf("%s",str_replace($fieldinfo,"_"," ")->name);
Hope this will work.
Wrong:
str_replace($fieldinfo,"_"," ")->name
Here you can not treat a string or array as an object.
Note: str_replace returns either string or array but not object;
printf("%s",str_replace("-","_","some-value")); //some_value
echo printf("%s",str_replace("-","_","some-value")); //some_value10 //10 is length of string
Hope this will help,
considering $fieldinfo has this value "sample_value_to_output"
$fieldinfo = "sample_value_to_output";
printf("%s",str_replace("_"," ",$fieldinfo));
this will output
sample value to output
your str_replace code is wrong
str_replace($fieldinfo,"_"," ")
it should be
str_replace("_"," ",$fieldinfo->name)

Trying to concat a string in php but it thinks its an array

Weird situation and I'm not even sure what to call it (hence unable to find any previous posts).
I'm passing in a variable that is a string as function, and then attempting to concat it to another string as such:
function saveFunction($number){
$myStr = "drawer-$number[]";
return $myStr;
}
So the output should be :
saveFunction("2")
"drawer-2[]"
However, because it thinks I am accessing $number as an array because of the brackets, the output is:
"0"
I even tried this:
function saveFunction($number){
$myStr = "drawer-$number";
return $myStr + "[]";
}
And got the same result.
Suggestions?
Double quotes in PHP are tricky. They interpret the string. This is why "drawing-$number" works in the first place.
Sometimes your string doesn't lend itself for automatic interpretation. You can use the always safe concatenation:
return "drawer-" . $number . "[]";
Or use {} to help the automatic detection:
return "drawer-{$number}[]"; // as opposed to: "drawer-{$number[]}"
Or use sprintf:
return sprintf("drawer-%s[]", $number); // %s because $number is actually a string, not an int
You can just concat the variable with the string like this:
<?php
function saveFunction($number){
return $myStr = "drawer-" . $number . "[]";
}
echo saveFunction("2");
?>
Output:
drawer-2[]
For further information see also: http://php.net/manual/en/language.operators.string.php

PHP -- int typecast of numeric string value giving 0

OK, so there is a page I'm querying on another server that returns a comma separated list of two values. Something it would return would be:
850,640
I have some PHP code that calls file_get_contents on that page and needs to do some numeric calculations based on the two values.
No matter what I try, I can't seem to get an int value out of this.
$res = trim(file_get_contents('http://thatURL/'));
echo "X" . $res . "X<br/>";
list($x,$y) = array_map(create_function('$a', 'return (int)$a;'), explode(',', $res));
echo "X:$x";
results in the output:
X 850,640 X
X:0
Note the spaces before and after the comma separated values(how the hell? I trim'd them!) and that $x is assigned the value 0.
What am I doing wrong here?
What am I doing wrong here?
Nothing, as far as I can see, which indicates that the content of $res is not quite what you expect. Could you change the first echo to:
echo htmlentities($res);
My guess is $res contains some un-printed characters, for example, it is actually:
<span> </span>850,640<span> </span>
or
850,640
Try the following. The array_map and llamda function are arguably overkill for your usage.
$res = " 850,640 ";
echo "X" . $res . "X<br/>";
list($x,$y) = explode(',', trim($res));
echo "X:" . (int)$x;
echo "Y:" . (int)$y;
Worked for me, but I'm not using file_get_contents(). If that doesn't work, something else is being output by the page.
PHP is not a typed language. Use intval to convert a string to integer.
Correction: it is a loosely typed language! That's what I meant!
Since I was using file_get_contents() on a URL, there was some HTML being put in as well that I didn't notice in my echo because it parsed out... just empty body and html tags. Oops!

String with Double quoted and Single quoted

i have a string with double quote like this
$count = 5;
$str = "result: $count";
echo $str; //result: 5
variable parsing work well, and my problem is $count var must be define later than $str
$str = "result: $count";
$count = 5;
echo $str; //result:
So i will use single quote and ask a question here to finding a way to parse var whenever i want
$str = 'result: $count';
$count = 5;
//TODO: parse var process
echo $str; //result: 5
I'm will not using regex replace.
For this type of thing, I'd probably use string formatting. In PHP, that'd be printf.
?php
$str="result: %d"
....dostuff.....define $count.....
printf($str,$count)
?
edit:
although, the best way to do this probably depends partly on why you have to define $string before $count.
If it's a string that's repeated a lot, and you wanted to put it in a global variable or something, printf would be my choice, or putting it in a function as other answers have suggested.
If the string is only used once or twice, are you sure you can't refactor the code to make $count be defined before $string?
finally, a bit of bland theory:
when you write '$string = "result: $count"',
PHP immediately takes the value of $count and puts it into the string. after that, it isn't worried about $count anymore, for purposes of $string, and even if $count changes, $string won't, because it contains a literal copy of the value.
There isn't, as far as I'm aware, a way of binding a position in a string to a yet-to-be-defined variable. The 'printf' method leaves placeholders in the string, which the function printf replaces with values when you decide what should go in the placeholders.
So, if you wanted to only write
$string = "result: $count"
$count=5
$echo string
(and not have to call another function)
and get
"result: 5",
there's no way to do that. The closest method would be using placeholders and printf, but that requires an explicit call to a function, not an implicit substitution.
Why don't you use a function?
function result_str($count) { return "result: $count"; }
preg_replace is the simplest method. Something like this:
$str = preg_replace("/\\$([a-z0-9_]+)/ie", "$\\1", $str);
But if you really don't want to use a regex, then you'll have to parse the string manually, extract the variable name, and replace it.

Categories