0
function test()
{   
$content = "lang=en]text en|lang=sp]text sp";
$atts = explode('|', $content);
}

What I'm trying to do is to allow myself to echo $param[en] to get "text en", $param[sp] to get "text sp". Is that possible?

  • the $content is actually from a database record.
1
  • 1
    What method was used to encode the data in that string? It looks home-grown, but perhaps you can refer to the generating code? Commented Feb 7, 2012 at 12:33

3 Answers 3

1
$param = array();
$langs = explode('|', $content);
foreach ($langs as $lang) {
    $arr = explode(']', $lang);
    $key = substr($arr[0], 5);
    $param[$key] = $arr[1];
}

This is if you are sure $content is well-formatted. Otherwise you will need to put in additional checks to make sure $langs and $arr are what they should be. Use the following to quickly check what's inside an array:

echo '<pre>'.print_r($array_to_be_inspected, true).'</pre>';

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

1

if this is not hard coded string in $content

function test()
{   
   $content = "lang=en]text en|lang=sp]text sp"; 
   $atts = explode('|', $content);
   foreach($atts as $att){
      $tempLang = explode("]", $att);
      $params[array_pop(explode("=", $tempLang[0]))] = $tempLang[1];
   }

   var_dump($params);
}

1 Comment

I'd do it the same way, but used list( $key, $value) = explode( "]", $att); instead. Anyway +1.
0

I think in this case you could use regular expressions.

$atts = explode('|', $content);
foreach ($atts as $subtext) {
    if (preg_match('/lang=(\w+)\](\w+) /', $subtext, $regs)) {
        $param[$regs[0]] = $regs[1];
   }
}

Although it seems that you have a bad database structure if that value comes from a database - if you can edit it, try to make the database adhere to make the database normal.

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.