preg functions and square brackets

He has: 296 posts

Joined: May 2002

Hello,

EDIT: I figured out a way around it without using any preg functions. It'd still be nice to know how I could do it.

I'm using preg_match and preg_replace to split a varibale. The variable can be in two forms: FOO[BAR]=NUM or FOO=NUM. My problem is the brackets in the first form (FOO[BAR]=NUM). I have a small script to TRY and get it to work but it isn't. Any ideas?

URL: http://necrotic.anitrade.net/test.php
Script:

<?php
$var
[] = \"USER[POST]=10\";
$var[] = \"BOSS=1\";

foreach(
$var as $this) {
  if (!preg_match(\"/[\",
$this)) {
   
$inpho = explode(\"=\",$this);
   
$info[] = Array (
             '1' =>
$inpho[0],
             '2' =>
$inpho[1],
      );
  } else {
   
$inpho = explode(\"=\",$this); // inpho[0] = USER[POST], inpho[1] = 10
   
$in2 = explode(\"[\",$inpho[0]); // in2[0] = USER, in2[1] = POST]
   
$in3 = explode(\"]\",$in2); // in3[0] = POST, in3[1] = ]
   
$info[] = Array (
             '1' =>
$inpho[0],
             '2' =>
$in2[0],
             '3' =>
$in3[0],
      );
  }
}

foreach(
$info as $foo ) {
  if (
$foo['3'] != '') {
    echo
$foo['1'].\"<br>\".$foo['2'].\"<br>\".$foo['3'].\"<p>\";
  } else {
    echo
$foo['1'].\"<br>\".$foo['2'].\"<p>\";
  }
}
?>

Any help you can provide would be most excellent.

Thanks,
necrotic

[James Logsdon]

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

<?php
$var
[] = \"USER[POST]=10\";
$var[] = \"BOSS=1\";
$var[] = \"USER[POST][TEST]=10\";
$var[] = \"USER['POST'][\\\"TEST\\\"]=10\";

foreach(
$var as $this) {
  unset(
$val);
 
  list(
$this, $val[]) = explode('=', $this);
 
  while (preg_match('/^([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)(\\[([\\'\"])?([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)(?(3)\\3)\\])?(.*)/',
$this, $match)) {
   
$val[] = $match[1];
   
$this = $match[4].$match[5];
  }
 
 
$info[] = $val;
}

foreach(
$info as $foo ) {
  echo implode(\"<br />\",
$foo) . \"<p>\\n\";
}
?>

Mark Hensler
If there is no answer on Google, then there is no question.

He has: 296 posts

Joined: May 2002

Awesome. I need to read more about the preg functions and all the uses.

One thing had to be changed:

<?php
preg_match
('/^([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[(['\"])?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(?(3)\3)\])?(.*)/
?>

The section (\[(['"]) needs to be (\[([\'\"]).

[James Logsdon]

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

grr..

vB2 has a problem with escaping things. I had to double escape everything, and I guess I missed that one. Good eye!

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.