Search code examples
phpstring-parsing

parse a spaced-string in php


guys i use Parse Post to receive my username and password But when my username included with Space its not work. my question is How can I parse a spaced-string in my php code?

<?php
function ParsePost( )
{
    $username = '';
    $password = '';

    $post = file_get_contents( "php://input" );

    $post = str_replace( "&", " ", $post );

    sscanf( $post, "%s  %s", $username, $password );

    return array( 'user' => $username,
              'pass' => $password
                );
}

?>

Solution

  • Just add:

    $post = str_replace( " ", "_", $post );
    

    Before:

    $post = str_replace( "&", " ", $post );
    

    The username will result with _s so you may want to convert them back to spaces before the return:

    $username = str_replace( "_", " ", $username);
    

    This will replace _ with a space as well.

    The best way to do this is actually using an explode.

    list($username, $password) = explode('$', $post);