This is my $var from json_encode:
{
"key1":"\u0000data1",
"key2":"\u0000data2",
"key3":"\u0000data3",
"key4":"\u0000data4
}
I would like to do this:
echo json_encode(str_replace ("\\u0000", "", $var));
in order to get rid of the preceding \u0000 that's showing up, the line above doesn't work to strip it.
You'll have to apply the function the other way round:
echo str_replace('\\u0000', '', json_encode($var));
This is because $var is an array. You'd have to iterate over all its entries and look for the \0 byte otherwise.
I ran into something similar.
This question & answer helped me understand the root cause of the problem.
I overcame this by realising that my class properties (equivalent to each keyn in your question) didn't really need to be protected. By making them public I side-stepped the issue altogether.
I suppose it's up to you to decide if this is best practice or suited to your project however.
Related
For example
$var = '10/2';
Is there a way for me to output the value 5 from that easily?
So something like this:
$foo = ($var) + 5;
I want $foo to have a value of 10?
Currently, the best way I know is to explode $var and then divide $var[0] by $var[1]. Is there a quicker way?
Another way of asking; Is there a way to tell the system to treat '10/2' as an equation instead of a string?
Could be you can use a solution like this
$foo = eval('return '.$var +5 .';');
print $foo;
eval require a line of code .. so you could build a valid code line
eval() to either assign in place or return:
eval("\$foo = ($var) + 5;");
$foo = eval("return ($var) + 5;");
First things first, EVAL IS HAZARDOUS AND SHOULD NEVER BE USED UNLESS YOU KNOW WHAT YOU'RE DOING! As an addendum to this, you don't know what you're doing. No matter how experienced you are as a programmer, when it comes to eval just assume you don't know what you're doing. Believe me, in the long run your sanity will thank you.
As for your problem, you're basically asking how to write an equation parser. Writing a full blown one that can handle all cases of valid input (and reliably identify invalid input) is a much bigger job than you might at first think, so if you really do need to parse string equations it may be better to look for a library that will do it for you because the chances are whoever wrote the library thought of a lot of stuff that you didn't, such as handling operator precedence and how parenthesis can modify it, how to pass strings in scientific notation, etc.
One of your comments suggests using PHP Math Parser. I've never personally used it, but I know the author by reputation well enough to believe it's a reliable library.
If your use case is always going to be as simple as your example then you can simply split the string and process the resulting fragments.
$parts = explode ("/", $var);
$foo = $parts[0] / $parts[1];
What is the best way to debug an array so that you can see what values are being stored and in what keys in the array they are being stored at? Also how do you make it so that it's easier to look at visually so that you don't have to keep looking through the array for the key and it's value in the one line print_r() function?
EDIT:
I now realize that print_r() is not the only solution to debugging arrays. So if you have alternate solutions that would be lovely as well to learn more about debugging.
EDIT2:
Ayesh K, ITroubs and Robert Rozas have mentioned both Krumo and Kint this far, if you have others feel free to post them. Also thanks to Raveren for writing Kint!
Every PHP developer should have a function for this. My function is below:
function r($var){
echo '<pre>';
print_r($var);
echo '</pre>';
}
To nicely print data, just call r($data);. If you want more detail, you could use this function:
function d($var){
echo '<pre>';
var_dump($var);
echo '</pre>';
}
here's mine...
demo: http://o-0.me/dump_r/
repo: https://github.com/leeoniya/dump_r.php
composer: https://packagist.org/packages/leeoniya/dump-r
you can restyle it via css if needed.
Everyone suggests print_r which is in core and works really well.
But when it comes to view a large array, print_r() drives me nuts narrowing down the output.
Give a try to krumo.
It nicely prints the array with visual formatting, click-expand and it also gives you the exact array key call that you can simply copy and paste.
<?php
krumo($my_array);
?>
Itroubs mentioned Kint as a better alternative to Krumo. (Thanks ITroubs!)
I use var_dump....now if you want some more, check out this site:
http://raveren.github.io/kint/
and
http://krumo.sourceforge.net/
The best practice to visually see the values/keys in an array is the following:
echo "<pre>".print_r($array,TRUE)."</pre>";
The true is required as it changes it into a string, the output will be:
array(
key1 => value,
key2 => value,
...
)
Quick solution: Open the source code of the page, and you'll see print_r's output in several lines and perfectly indented.
print_r is not one lined (it uses \n as new line, not <br>). Add a <pre>...</pre> around it to show the multiple lines.
print_r() uses \n as its line delimiter. Use <pre> tags or view the page's source code to make it look right. (on Windows, Linux works with \n)
You can either look source code or use var_dump() or print_r() with <pre>...</pre>
I personally, never liked all this fancy stuff, i use print_r() because it's not overwhelming and it gives enough information.
Here is mine:
if(isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Debug')
{
echo '<strong><i>FILE : </i></strong>'.__FILE__.'<strong> <i>LINE : </i></strong>'.__LINE__.'<pre>';
print_r($var);
echo '</pre>';
die;
}
This if statement is to ensure that other people don't see what you've printed.
There is a good add-on for Mozila-Firefox and Google Chrome called "user agent switcher", where you can create your custom user agents. So I create a user agent called "Debug", and when I'm working, I change the user agent.
If I use default user agent nothing will happen and the page wont die;, only you and people who also change the user agent to "Debug" will see the printed variable. This is helpful if you want to debug a problem in a production environment, and you don't want the page to die; and it is also good if other people are also working on the project and you don't want to interrupt them by killing the page.
Then I echo out the current File and Line, this is helpful when you work in a framework or CMS or any other big project with thousands of files and folders, and while debugging, if you might forget where you've typed die; or exit; and you need to remember where you've been and which variables you have printed.
I use the NetBeans IDE for PHP development, I have a macro set up so when you select a variable and use it, it will paste this debugging tool to the text editor and put the selection inside a print_r(); function. If you also use NetBeans, you can use this macro:
cut-to-clipboard
"if(isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Debug')"
insert-break
"{"
insert-break
"echo '<strong><i>FILE : </i></strong>'.__FILE__.'<strong> <i>LINE :</i></strong>'.__LINE__.'<pre>';"
insert-break
"print_r("
paste-from-clipboard
remove-line-begin
");"
insert-break
"echo '</pre>';"
insert-break
"die;"
You just need to select the $variable and use the macro.
To be honest, I'm surprised that print_r() (print human-readable). There are three native functions which each have their advantages and disadvantages in printing data to a document. As mentioned elsewhere on the page, wrapping your output in <pre> ... </pre> tags will be very beneficial in respecting newlines and tabbing when printing to an html document.
The truth is that ALL php developers, from newbie to hobbyist to professional to grand wizard level 999, need to have the following techniques in their toolbox.
Here is a non-exhaustive demo which exposes some of the differences.
var_export() is the format that I use most often. This function wraps strings in single quotes. This is important in identifying trailing whitespace characters and differentiating numeric types versus string types. To maintain the integrity of the output data and permit instant portability of the data into a runnable context, single quotes and backslashes are escaped -- don't let this trip you up.
print_r() is probably my least-used and the least-informative function when data needs to be inspect. It does not wrap strings in any kind of delimiting character so you will not be able to eyeball invisible characters. It will not escape backslashes, single quotes, or double quotes. It wraps keys in square braces which may cause confusion if your keys contain square braces originally.
var_dump() is uniquely powerful in that it expresses data types AND the byte count for strings. This is hands-down the best tool when there is a risk that you might have unexpected multibyte characters interfering with the success/stability of your script.
Depending on your php version and which function you use, you may see differing values with same input data. Pay careful attention to float values.
debug_zval_dump() very much resembles the output of var_dump(), but also includes a refcount. This native function is not likely to provide any additional benefit relating to "debugging an array".
There are also non-native tools which may be of interest (most of which I've never bothered to use). If you are using a framework, Laravel for instance, offers dd() (dump and die) as a diagnostic helper method. Some devs love the collapsed/expandable styling of this tool, but other devs loudly voice their annoyance at the tedious clicking that is necessary to expose nested levels of data.
As a sideways approach to printing iterable data, you could entertain the idea of echoing a json-encoded string with the JSON_PRETTY_PRINT. This may reveal some things that could cause trouble like multibyte and whitespace characters, but don't forget that this is literally "encoding" the data. In other words, it is converting data from one form to another and it will mutate certain occurrences in the process. Like var_export(), a json encoded string is an excellent form to maintain data integrity when it needs to be tranferred from one place to another (like from your project to your Stack Overflow question!).
{$row['info']}
How do I use stripslashes() php function on this?
I've tried :
stripslashes({$row['info']}), doesnt work and this: {stripslashes($row['info'])}
Neither work.
Do I have to use a $var first??
Thanks
stripslashes returns the modified string, leaving its argument unchanged. You have to assign the result to a variable:
$var = stripslashes($row['info']);
That said, why are you doing this? You almost certainly shouldn't be. There is no reason to strip slashes on data coming from the database, unless you've double-escaped the slashes when the data was inserted.
Your question is somewhat confusing.
stripslashes() takes parameter and converts backslashed symbols to normal ones. more over, it does not affect the parameter. it returns stripped version.
so $result = stripslashes($source) or $row["info"] in your case.
$var = stripslashes($row['info']);
is more correct. Or in string, use it like this
echo "something".stripslashes($row['info'])." some more thingy";
It almost seems, that you are using heredoc syntax because of your {}. Question, is why? Are you seriously displaying your results like this?:
echo <<<my_results
Info: {$row['info']}
my_results;
Well, since that is cool way to do so then here is your fix:
$row_info = stripslashes($row['info']);
echo <<<my_results
Info: {$row_info}
my_results;
However, I do not recommend that approach. Rather do it like this:
echo 'Info:' . stripslashes($row['info']);
Because {stripslashes($row['info'])} doesn't work indeed and stripslashes({$row['info']}) is an anecdote!
Is there any fast (regex-based?) method to replace all smileys in a text, each by an unique corresponding identifier? For example, the first occurrence of :) should be replaced by smiley1, the :)) by smiley2 and another occurrence of :) by smiley1 again? Furthermore, the identifyier should be the same using different text for input
Any potential combination of the typical symbols (<5 chars?) such as :;-()&%}{[]D<>30_o should be recognizable.
Can this be done without a generating a large array of all combinations? In case, how?
Are you looking for preg_replace_callback()? You can even use closures in php 5.3. I am not clear on what the objective is, so at this point this is the best I can provide, if you can clarify, then maybe I can see what I can come up with for sample code.
edit, here's an example from the PHP manual. Doesn't help in this case specifically, but if you just change the regex, the function and the string (basically everything, lol), then it will do the job:
<?php
echo preg_replace_callback('/-([a-z])/', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>
I don't understand why you can't do:
str_replace(":))","<img src=\"smiley1.jpg\">",$STRING)
str_replace(":)","<img src=\"smiley2.jpg\">",$STRING)
etc... seems to be the most simple solution and logical
Obviously, it cannot be done by using such a str_replace. How would you fetch a ":)))" or maybe a "-.-" which is also not present in your list? Enumerating all potential smileys is a hard task, resulting in n!/(n-k)! candidates. Here, in the example provided above n=18 and k=5...
Thus, I'm asking for a way to use a regex - but I don't how to replace each combination of chars which is intended to represent a smiley each time by the same text.
Idea: is it possible to use a callback function in combination with a hash?
Yeah, Tim! That is exactely what came into my mind when writing the last post. So the solution is
<?php
echo preg_replace_callback("/([\)\(\[\]<>#-\.:;*+{}]{2,9})/", function ($match) {
return " ".md5($match[1])." ";
}, ':::-) :-)) nope (yeah) cool:) }:)');
?>
Thanks!
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php
eval ("\$text_including_tax = \"$text_including_tax\";");
Scrap my previous answer.
The reason this eval() is here is shown in the php eval docs
This is what's happening:
$text_including_tax = '$tax ...';
...
$tax = 10;
...
eval ("\$text_including_tax = \"$text_including_tax\";");
At the end of this $text_including_tax is equal to:
"10 ..."
The single quotes prevents $tax being included in the original definition of the string. By using eval() it forces it to re-evaluate the string and include the value for $tax in the string.
I'm not a fan of this particular method, but it is correct. An alternative could be to use sprintf()
This code seems to be a bad way of forcing $text_including_tax to be a string.
The reason it is bad is because if $text_including_tax can contain data entered by a user it is possible for them to execute arbitrary code.
For example if $text_include_tax was set to equal:
"\"; readfile('/etc/passwd'); $_dummy = \"";
The eval would become:
eval("$text_include_tax = \"\"; readfile('/etc/passwd'); $_dummy =\"\";");
Giving the malicious user a dump of the passwd file.
A more correct method for doing this would be to cast the variable to string:
$text_include_tax = (string) $text_include_tax;
or even just:
$text_include_tax = "$text_include_tax";
If the data $text_include_tax is only an internal variable or contains already validated content there isn't a security risk. But it's still a bad way to convert a variable to a string because there are more obvious and safer ways to do it.
I'm guessing that it's a funky way of forcing $text_including_tax to be a string and not a number.
Perhaps it's an attempt to cast the variable as a string? Just a guess.
You will need the eval to get the tax rate into the output. Just moved this to a new server and for some reason this line caused a server error. As a quick fix, I changed it to:
//eval ("\$text_including_tax = \"$text_including_tax\";");
$text_including_tax = str_replace('$tax', $tax, $text_including_tax);
It is evaluating the string as PHP code.
But it seems to be making a variable equal itself? Weird.
As others have pointed out, it's code written by someone who doesn't know what on earth they're doing.
I also had a quick browse of the code to find a total lack of text escaping when putting HTML/URIs/etc. together. There are probably many injection holes to be found here in addition to the eval issues, if you can be bothered to audit it properly.
I would not want this code running on my server.
I've looked through that codebase before. It's some of the worst PHP I have seen.
I imagine you'd do that kind of thing to cover up mistakes you made somewhere else.
No, it's doing this:
Say $text_including_tax = "flat". This code evaluates the line:
$flat = "flat";
It isn't necessarily good, but I did use a technique like this once to suck all the MySQL variables in an array like this:
while ($row = mysql_fetch_assoc($result)) {
$var = $row["Variable_name"];
$$var = $row["Value"];
}