2

My methods parse strings and do stuff with the information contained in the string. a simple example would be

$string=
"
    user:name,password={$_POST['name']}, {$_POST['password']}(md5); 
    names:name=name;
";
$class->$method($string);

The above would do two insert statements. The first will insert in a table named user the users name and the password encypted in md5.
the second would insert a name in the names table. I'm having setting it up so that characters can be escaped. ie if the users name was p;ez. The string would have p\;ez.
My current method is as follows

    #get position of ;
    $offsetSemi=stripos($s, ";");
    #check if its escaped
    if ($s[$offsetSemi-1]!='\\')
    {
        //not escaped
    }

the problem with the above method is that it will only check the first instance of ;. the other solution i tried was exploding the string on ;. however this would not work because it exploded on all instances including ones that were escaped. the other thing i tried was an explode with the regular expression below

/[^\\\];/

the prolem with this is that it exploded on the charecter before ; on all the instances that were not escaped. is there a way i can explode a string on all instances of ; that are not preceded by a backslash?

Yamiko
  • 5,303
  • 5
  • 30
  • 52
  • 1
    Does your input **have** to be in that convoluted format? If not, you should consider using a format that has built in parsers like JSON on XML. – PPrice Aug 11 '11 at 22:43
  • no it does not. I'm not familiar with json or xml. I have heard of them but never had learned or used them up to date. Can you suggest a page that has an example of parsing xml or json? – Yamiko Aug 11 '11 at 22:51

3 Answers3

2

Instead of exploding you can parse the string:

$arr = array();
$tmp = "";

for ($i = 0; $i < strlen($s); $i++) {
   switch ($s[$i]) {
      case "\\":
         if ($i < strlen($s) - 1) $tmp .= $s[$i++] . $s[$i++];
      break;
      case ";":
         $arr[] = $tmp;
         $tmp = "";
      break;
      default:
         $tmp .= $s[$i];
   }
}

if (strlen(trim($tmp)) > 0) { // last section
    $arr[] = $tmp;
}
fardjad
  • 20,031
  • 6
  • 53
  • 68
2

Consider using JSON for you input format. Since you are using PHP you could check out this intro to JSON and PHP. Also, you will need to use json_encode() and json_decode(). With those functions you can easily convert a JSON string to a PHP object or associative array and back again if needed. There is no need for you to worry about the tokenizing/parsing step if you start with a format that has built in parsing help.

If you want to go with XML then you could use SimpleXML or DOM. But, you would be best served by using JSON.

PPrice
  • 2,243
  • 17
  • 12
0

Write a parser. Tokenize your input first, then look at it.

Halcyon
  • 57,230
  • 10
  • 89
  • 128