phpbar.de logo

Mailinglisten-Archive

[php] String mit Escape-Zeichen verarbeiten

[php] String mit Escape-Zeichen verarbeiten

Roland Tapken ml at lalamuhkuh.de
Mit Aug 18 13:50:16 CEST 2004


Hi Roland, 

und mal wieder Antworte ich mir selbst :-)

Für den Fall, dass mal jemand vor einem ähnlichen Problem steht:

/**
 * This function will parse a string like the php-interpreter would do.
 * In double quotes, \n will become a newline, \r a carriage return, \"
 * a double quote. In single quotes, \' will become '.
 * You can use \\ to get a single backslash.
 *
 * Written by Roland Tapken <r.tapken at icreatix.net>.
 */
function parsestring($str) {
  // Active quoting modes...
  $quotesingle = false;
  $quotedouble = false;
  $backslash   = false;
  
  $strlen = strlen($str);
  $newstr = '';
  for ($pos = 0; $pos < $strlen; $pos++) {
    $char = substr($str, $pos, 1);
    if ($backslash) {
      if ($quotesingle) {
        // Singlequotes will not parse for special characters...
        // The only escapable chars ar ' and \.
        $newstr .= ($char == '\\' || $char == '\'') ? $char :
'\\'.$char;      } else {
        // Find some special characters...
        switch ($char) {
          case 'n':
            $newstr .= "\n"; break;
          case 'r':
            $newstr .= "\r"; break;
          case 't':
            $newstr .= "\t"; break;
          case '"':
            $newstr .= '"'; break;
          default:
            $newstr .= "\\".$char; // Not an escapable character
        }
      }
      $backslash = false;
    } else {
      // Find normal or escape characters
      switch ($char) {
        case '"':
          if ($quotesingle) {
            $newstr .= $char; break;
          }
          $quotedouble = !$quotedouble;
          break;
          
        case "'":
          if ($quotedouble) {
            $newstr .= $char; break;
          }
          $quotesingle = !$quotesingle;
          break;
        
        case '\\':
          $backslash = true; break;
          
        default:
          $newstr .= $char;
      }
    }
  }

  if ($quotesingle || $quotedouble || $backslash)
    return false; // Unexpected end of string
  else
    return $newstr;
}



Bye, Roland
-- 
Es ist schon über so viele Sachen Graß gewachsen, dass
man bald keiner Wiese mehr trauen kann!

php::bar PHP Wiki   -   Listenarchive