3

I got stuck with the nuance:

//1 - get mysql results into array
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {

    array_push($my_array, $row['fruit_name']);

}

//2 - sort array
sort($my_array);

//3 - convert array to json
json_encode($my_array);

OUTPUT:

['banana\r', 'apple\r', 'orange\r']



I have tried to remove \r with str_replace("\r", "", $my_array), but to no avail.
It seems str_replace does not work for any replace at all

Thanks!

1
  • What is your input? Please write in your question. Commented Nov 24, 2015 at 5:50

4 Answers 4

3

You will need to escape twice

str_replace("\\r", "", $my_array);
Sign up to request clarification or add additional context in comments.

Comments

0

You are not using str_replace in proper manner.

In PHP, if you need to match literal backslash, then you need to use 4 backslashes together.

Try this:

$json = json_encode($my_array);

str_replace("\\\\r", "", $json);

2 Comments

Strange. i have a working code where, 4 backslashes are working and 2 are not. ["banana", "apple", "orange"] This is what I get after using 4 backslashes. After 2 backslashes I get this ["banana\","apple\","orange\"]
It might be just my php configuration or something like that.
0

Try this

sort(str_replace("\\r", "", $my_array));

str_replace("\\\\r", "", $json);`

Comments

0

You should consider removing carriage return before array_push. Adding it with carriage return and then removing it is not logical.

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
   array_push($my_array, str_replace("\r", '', $row['fruit_name']));
}

//2 - sort array
sort($my_array);

//3 - convert array to json
json_encode($my_array);

Sample code

<?php
$array = array(
    "xxx\r",
    "yyy\r"
);

echo json_encode($array) . "\n";

array_walk($array, function(&$item, $key){
    $item = str_replace("\r", '', $item);
});

echo json_encode($array) . "\n";
?>

Result

["xxx\r","yyy\r"]
["xxx","yyy"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.