faressoft
faressoft

Reputation: 19651

How can i extract a username from string using regexp in php

How can i extract a username from string using regexp in php

<?php

$myString = "user=anas fares,pass=245654323456543dfgf345rgghf5y";

//result should be :

$username = "anas fares";
$password = "245654323456543dfgf345rgghf5y";

//remember, I dont know if username is anas fares or anything else.

?>

Upvotes: 0

Views: 314

Answers (2)

Alin P.
Alin P.

Reputation: 44346

A. Non-regex approach.

// deprecated //
list($username, $password) = explode(',', $myString);
$username = explode('=', $username);
$username = str_replace('+', ' ', $username[1]);
$password = explode('=', $password);
$password = $password[1];

// new version, independent of order //
$pairs = explode(',', $myString);
foreach($pairs as $pair){
    list($key, $value) = explode('=', $pair);
    $results[$key] = str_replace('+', ' ', $value);
}
// $results['user']
// $results['pass']

B. Regex.

/^user=([^,]*),pass=(.*)$/

C. parse_str. This one I recommend and it's probably the best option.

parse_str(str_replace(',', '&', $myString), $results);

Upvotes: 4

Lekensteyn
Lekensteyn

Reputation: 66465

if(preg_match('/^user=(.+?),pass=(.+?)$/', $myString, $matches)){// if there's no match, this won't be executed
   $username = $matches[1];
   $password = $matches[2];
}

If you know what characters are allowed, it's recommended to use character classes instead or .. E.g., you know that the password only contains characters a-z (lowercase only) and 0-9, you should replace the second (.+?) by [a-z0-9]+?. If you even know it's a fixed length , in case of a MD5 hash, you should replace +? by {32} (md5 has a fixed length of 32)

Upvotes: 5

Related Questions