json_encode() works for one string but not another? - php

EDIT:
Solved. Somebody commented with an answer, but then deleted it. Embarrassingly, the problem was fixed by adding semi-colons after the two json_encode lines. I still have no idea why string1 worked without a closing semi-colon and string2 did not, but it works, so… success?
/EDIT
Hi… fairly nooby programmer here.
Within PHP, I'm grabbing two arrays from my database. This works fine. I then implode each array into a string. This too works fine.
Later in the same file, in the javascript section of my code (featuring jQuery), I do:
string1 = <?php echo json_encode($string_1);?>
string2 = <?php echo json_encode($string_2);?>
Encoding string1 works perfectly… so long as I comment out the string2 line entirely. It kills my page.
I've tried ensuring that my string is utf8-encoded. I've tried ensuring that there are no backslashes or other problematic characters. Currently, I've got some dummy code that's designed to be as unproblematic as possible… still doesn't work.
Here's the skeleton version of it.
PHP:
$array1 = array();
$array2 = array();
$i = 1;
while($row = mysqli_fetch_assoc($query_result)) {
$array1[$i] = $row['column1'];
$array2[$i] = $row['column2'];
$i++;
}
$string1 = implode(",", $array1);
$string2 = "oh_come_on_why_doesnt_this_work"; // implode(",", $array2);
And JS/HTML/JQuery:
var string1;
var string2;
$.getScript("js/set_functions.js", function(){ loadedScript() });
function loadedScript() {
string1 = <?php echo json_encode($string1);?>
string2 = <?php echo json_encode($string2);?>
// string2 = <?php echo "'" . $string2 . "'";?> doesn't work either
alert(string1); // works if I comment out both string2 = … lines
alert(string2); // displays "undefined" if the first string2 = … line is commented…
// …out, doesn't display at all if it isn't
}
STUCK PLEASE HELP.
Let me know if you need to see more of my code, or if there's anything else I could do to help make this question better. Thanks.
PS: I'm not a good programmer, I know. Please don't correct my other bad coding habits IN LIEU OF helping solve this problem. Thanks!
EDIT: Sorry, in response to Joe Fraumbach, that was an error in my copy-pasting. I had actually declared $array2 = array();

EDIT: You are missing semicolons at the end of the JS assignment expressions, which in some cases will cause parsing problems: both lines may become part of a single, multiassignment expression. Try adding them and see if that fixes your problem.
string1 = <?php echo json_encode($string1); ?>;
string2 = <?php echo json_encode($string2); ?>;
Note that json_encode only works with UTF-8. So if you're not sure that its input is UTF-8, utf8_encode() the strings you feed it, otherwise the whole string is rendered as null in PHP (and translated into an empty string upon concatenation).

$array2 is never defined. You defined $array1 = array();. Do the same for $array2.

Related

PHP -- replace text in an array constructed from file php function

I have string and I would like to remove words which are part of the string and in the array. The array was created using the file function and the preg_replace function to delete patterns from the array occurring within a sentence.
Although, I am not getting errors, the replace is not working. I would really appreciate any help, I have been trying to get it to work these last 3 days but I haven't managed to do so :( and it is driving me crazy.
This is what I have done so far:
PHP code:
$test=file('files/stop_words.txt');
echo $test;
$no_stop=str_replace('|$test|', 'lllll', $sentence);
echo "<br>" .$no_stop;
Stop_words.txt file excerpt:
|alone|
|along|
|alongside|
|already|
|also|
|although|
|always|
|am|
|amid|
|amidst|
|among|
|amongst|
|an|
Thanks
I am adding a sample sentence so you can see it working.
I swapped out file with file_get_contents so that you could remove the | on each side before doing the check.
str_replace can accept an array, but it must be setup for exact matches, so having "|among|" instead of just "among" would hinder as well.
$sentence = "I stood alone in the yard";
$test = file_get_contents('files/stop_words.txt'); // Load in as a string
$test = str_replace("|", "", $test); // Remove unneeded |
$testList = explode("\n", $test); // Turn into an array
$filtered_sentence = str_replace($testList, 'lllll', $sentence); // Pass array into str_replace
echo $filtered_sentence;

php url query nested array with no index

I'm working with a third party API that receives several parameters which must be encoded like this:
text[]=Hello%20World&text[]=How%20are%20you?&html[]=<p>Just%20fine,%20thank%20you</p>
As you can see this API can accept multiple parameters for text, and also for HTML (not in the sample call).
I have used http_build_query to correctly build a query string for other APIs
$params['text'][] = 'Hello World';
$params['text'][] = 'How are you?';
$params['html'][] = '<p>Just fine, thank you</p>';
$http_query = http_build_query($params);
The problem with this approach is that it will build a query string with the numeric index:
text[0]=Hello%20World&text[1]=How%20are%20you?&html[0]=<p>Just%20fine,%20thank%20you</p>
unfortunately the API I'm working with doesn't like the numeric index and fails.
Is there any php function/class-method that can help me build a query like this quickly?
Thank you
I don't know a standard way to do it (I think there is no such way), but here's an ugly solution:
Since [] is encoded by http_build_query, you may generate string with indices and then replace them.
preg_replace('/(%5B)\d+(%5D=)/i', '$1$2', http_build_query($params));
I very much agree with the answer by RiaD, but you might run into some problems with this code (sorry I can't just make this a comment due to lack of rep).
First off, as far as I know http_build_query returns an urlencode()'d string, which means you won't have [ and ] but instead you'll have %5B and %5D.
Second, PHP's PCRE engine recognizes the '[' character as the beginning of a character class and not just as a simple '[' (PCRE Meta Characters). This may end up replacing ALL digits from your request with '[]'.
You'll more likely want something like this:
preg_replace('/\%5B\d+\%5D/', '%5B%5D', http_build_query($params));
In this case, you'll need to escape the % characters because those also have a special meaning. Provided you have a string with the actual brackets instead of the escapes, try this:
preg_replace('/\[\d+\]/', '[]', $http_query);
There doesn't seem to be a way to do this with http_build_query. Sorry. On the docs page though, someone has this:
function cr_post($a,$b=0,$c=0){
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v){
if ($c) $k=$b."[]"; elseif (is_int($k)) $k=$b.$k;
if (is_array($v)||is_object($v)) {
$r[]=cr_post($v,$k,1);continue;
}
$r[]=urlencode($k)."=" .urlencode($v);
}
return implode("&",$r);
}
$params['text'][] = 'Hello World';
$params['text'][] = 'How are you?';
$params['html'][] = '<p>Just fine, thank you</p>';
$str = cr_post($params);
echo $str;
I haven't tested it. If it doesn't work then you're going to have to roll your own. Maybe you can publish a github gist so other people can use it!
Try this:
$params['text'][] = 'Hello World';
$params['text'][] = 'How are you?';
$params['html'][] = '<p>Just fine, thank you</p>';
foreach ($params as $key => $value) {
foreach ($value as $key2 => $value2) {
$http_query.= $key . "[]=" . $value2 . "&";
}
}
$http_query = substr($http_query, 0, strlen($http_query)-1); // remove the last '&'
$http_query = str_replace(" ", "%20", $http_query); // manually encode spaces
echo $http_query;

How to remove commas between double quotes in PHP

Hopefully, this is an easy one. I have an array with lines that contain output from a CSV file. What I need to do is simply remove any commas that appear between double-quotes.
I'm stumbling through regular expressions and having trouble. Here's my sad-looking code:
<?php
$csv_input = '"herp","derp","hey, get rid of these commas, man",1234';
$pattern = '(?<=\")/\,/(?=\")'; //this doesn't work
$revised_input = preg_replace ( $pattern , '' , $csv_input);
echo $revised_input;
//would like revised input to echo: "herp","derp,"hey get rid of these commas man",1234
?>
Thanks VERY much, everyone.
Original Answer
You can use str_getcsv() for this as it is purposely designed for process CSV strings:
$out = array();
$array = str_getcsv($csv_input);
foreach($array as $item) {
$out[] = str_replace(',', '', $item);
}
$out is now an array of elements without any commas in them, which you can then just implode as the quotes will no longer be required once the commas are removed:
$revised_input = implode(',', $out);
Update for comments
If the quotes are important to you then you can just add them back in like so:
$revised_input = '"' . implode('","', $out) . '"';
Another option is to use one of the str_putcsv() (not a standard PHP function) implementations floating about out there on the web such as this one.
This is a very naive approach that will work only if 'valid' commas are those that are between quotes with nothing else but maybe whitespace between.
<?php
$csv_input = '"herp","derp","hey, get rid of these commas, man",1234';
$pattern = '/([^"])\,([^"])/'; //this doesn't work
$revised_input = preg_replace ( $pattern , "$1$2" , $csv_input);
echo $revised_input;
//ouput for this is: "herp","derp","hey get rid of these commas man",1234
It should def be tested more but it works in this case.
Cases where it might not work is where you don't have quotes in the string.
one,two,three,four -> onetwothreefour
EDIT : Corrected the issues with deleting spaces and neighboring letters.
Well, I haven't been lazy and written a small function to do exactly what you need:
function clean_csv_commas($csv){
$len = strlen($csv);
$inside_block = FALSE;
$out='';
for($i=0;$i<$len;$i++){
if($csv[$i]=='"'){
if($inside_block){
$inside_block=FALSE;
}else{
$inside_block=TRUE;
}
}
if($csv[$i]==',' && $inside_block){
// do nothing
}else{
$out.=$csv[$i];
}
}
return $out;
}
You might be coming at this from the wrong angle.
Instead of removing the commas from the text (presumably so you can then split the string on the commas to get the separate elements), how about writing something that works on the quotes?
Once you've found an opening quote, you can check the rest of the string; anything before the next quote is part of this element. You can add some checking here to look for escaped quotes, too, so things like:
"this is a \"quote\""
will still be read properly.
Not exactly an answer you've been looking for - But I've used it for cleaning commas in numbers in CSV.
$csv = preg_replace('%\"([^\"]*)(,)([^\"]*)\"%i','$1$3',$csv);
"3,120", 123, 345, 567 ==> 3120, 123, 345, 567

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!

PHP - Error parsing a string with code

I'm having a problem with some code that used to work in PHP 4.X and is not working in PHP 5.2.4
First of all, there is a small example of a code similar to the one is causing the problem. Unfortunately, I haven't been able to reproduce the problem with a small example.
<?php
class Example{
public function showExample()
{
$ind = 1;
$m = "method";
$str2 = "{call method}";
$str2 = str_replace("{call $m}" , "<?php print( \$pre$ind ); ?>", $str2);
echo $str2 . "\n";
}
}
$e = new Example();
$e -> showExample();
?>
What this code is doing is building a string with some php code to execute later on. In particular, the code generated will print the value of a variable named "$pre" + a variable number. In this case, the output is the following:
<?php print( $pre1 ); ?>
Everything runs fine with this code. The problem is when I use it in the context of a much bigger class, that is part of a framework I've been using for a long time. I cannot paste here the whole source of the class, but the problematic lines are the following (I simplified them a little bit to remove the str_replace, but the error still appears):
$myVar = "value";
$myVar2 = 2;
$str2 = "<?php print( \$myVar$myVar2 ); ?>";
When I load the file, I get the following two messages:
PHP Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /Users/giove/Sites/mundial/htmltemplate.php on line 252
PHP Parse error: syntax error, unexpected T_VARIABLE in /Users/giove/Sites/mundial/htmltemplate.php on line 252
I can fix the warning by removing the '\', but that changes the semantics of the code, so it's not a real possibility.
Now, the weirdest part is I can remove both errors by breaking or removing the sequence "
This seems to be a difference in versions, but I haven't been able to find any mention to it on the change logs.
Now I've got a working solution from Cryo: split the string
"<?php"
to prevent its 'evalution' (I'm not sure if that's really an evaluation).
Nevertheless, I still would like to know the reason for this weird behavior.
Cryo: thanks for your help, I'll mark the question as answered in a couple of days.
My guess is that PHP is catching on the re-opening of the php tag <?php, try splitting just that:
$str2 = "<?" . "php print( \$myVar$myVar2 ); ?>";
Or use single quotes and concatenation:
$str2 = '<?php print( $myVar' . $myVar2 . ' ); ?>';
Cryo is on the right track, though I think the actual issue is that PHP evaluates variables within double-quoted strings. However, the slash should prevent the variable from being evaluated. So:
$a = "somestring"
$b = "\$a" // -> \$a
$c = '\$a' // -> \$a
I think your string is getting evaluated in an odd way such that the \ + $myVar is evaluated in a strange way.

Categories