1

I have a drag and drop JS plugin that saves strings as the following:

["кровать","бегемот","корм","валик","железосталь"]

I have found that I can use str_replace in an array to remove both brackets and " char. The issue that I now have is that I have a invalid argument for passing through the foreach loop as it cannot distinguish each individual word.

$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str = str_replace(str_split('[]"'), '', $bar);

foreach($new_str as $arr){

    echo $arr;

}

So the data now outputted looks as follows (if I were to echo before the foreach loop):

кровать,бегемот,корм,валик,железосталь

Is there anyway in which I can use a comma as a delimeter to then pass this through the foreach, each word being it's own variable?

Is there an easier way to do this? Any guidance greatly appreciated!

Liam-FD
  • 67
  • 9
  • 8
    is that json? you should probably just `json_decode()` it. – Marc B Jul 29 '16 at 15:30
  • `foreach(explode(',',$new_str) as $arr)` But, as above, the js is using a regular js array. If you show how you are passing this to php, there will be a better solution – Steve Jul 29 '16 at 15:31

4 Answers4

2

The function you need is explode(). Take a look here: http://www.w3schools.com/php/func_string_explode.asp

Look at the following code:

$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str = str_replace(str_split('[]"'), '', $bar);
$exploding = explode(",", $new_str);

foreach($exploding as $token){

    echo $token;

}
Antoni
  • 2,071
  • 2
  • 24
  • 31
2

Technically, you can use explode, but you should recognize that you're getting JSON, so you can simply do this:

$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str = json_decode($bar);

foreach($new_str as $arr){

    echo $arr;

}

With no weird parsing of brackets, commas or anything else.

charmeleon
  • 2,693
  • 1
  • 20
  • 35
2

It looks like you've got a JSON string and want to convert it to an array. There are a few ways to do this. You could use explode like this:

$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str = str_replace(str_split('[]"'), '', $bar);
$new_str_array = explode($new_str);

foreach($new_str_array as $arr){

    echo $arr;

}

or you could use json_decode like this:

$bar = '["кровать","бегемот","корм","валик","железосталь"]';
$new_str_array = json_decode($bar);

foreach($new_str_array as $arr){

    echo $arr;

}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
user1958756
  • 377
  • 1
  • 4
  • 17
1
<?php
    $aa = '["кровать","бегемот","корм","валик","железосталь"]';
    $bb = json_decode($aa);
    foreach($bb as $b)
     echo $b."\n";
?>

and the results is,

кровать
бегемот
корм
валик
железосталь
LF00
  • 27,015
  • 29
  • 156
  • 295