How can I convert this string to array?

Total Post:88

Points:616
JSON 
 2081  View(s)
Ratings:
Rate this:

I am stucked with converting the string of specific format to array. Spliting the string using explodedoesn't seems to be the right approach and i am not so good with regular expressions. So my question is how can i convert the following string to array?

Current format of the string


maxWidth: 800,

openEffect: elastic,
closeEffect: elastic,
helpers : {
       title : {
             type: outside
           },
       thumbs : {
              width : 50,
              height : 50
            }
      }


Desired Array

array(

  'maxWidth' => 800,
  'openEffect' => 'elastic',
  'closeEffect' => 'elastic',
  'helpers' => array(
               'title' => array('type' => 'outside'),
               'thumbs' => array('width' => 50, 'height' => 50)
             )
)


Any help would be greatly appreciated.

  1. Post:25

    Points:175
    Re: How can I convert this string to array?

    The string in your example is almost a valid JSON (JavaScript Object Notation) structure!

    Here's what your string would look like as valid JSON

     {
    
        "maxWidth": 800,
        "openEffect": "elastic",
        "closeEffect": "elastic",
        "helpers": {
            "title": {
                "type": "outside"
            },
            "thumbs": {
                "width": 50,
                "height": 50
            }
        }
    }

    So our approach (as suggested by @WiseGuy) would be to first inject a few characters with preg_replace to Turn your string init into valid JSON:

    $str = preg_replace('/\b/' , '"' , $str);
    
    $str = '{' . $str . '}';

    The regex above is using the Word Boundaries anchor to add quotation marks around all words. Then we wrap the whole thing in curly braces and voilà, we've got a x-language compatible object format.

      Modified On Mar-31-2018 05:05:39 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!