Search code examples
phpsubstrstrpos

I have a problem with the strpos & substr function on PHP


I have a problem with the strpos & substr function, thank you for your help:

$temp = "U:hhp|E:123@gmail.com,P:h123";

$find_or = strpos($temp,"|");
$find_and = strpos($temp,",");

$find_user = substr($temp,2,$find_or-2);
$find_email = substr($temp,$find_or+3,$find_and);
$find_passeord = substr($temp,$find_and+3,strlen($temp));

echo("$find_user+$find_email+$find_passeord<br/>");

/************************************/

Why is the output like this ??

hhp+123@gmail.com,P:h123 +h123

but i want this:

hhp+123@gmail.com,h123

Solution

  • The problem is that $find_and is the index of ,, but the third argument to substr() needs to be the length of the substring, not the ending index. So

    $find_email = substr($temp,$find_or+3,$find_and);
    

    should be

    $find_email = substr($temp,$find_or+3,$find_and-$find_or-3);
    

    For $find_passeord you can omit the 3rd argument, since the default is the end of the string.

    However, this would be simpler with a regular expression:

    if (preg_match('/^U:(.*?)\|E:(.*?),P:(.*)/', $temp, $match)) {
        list($whole, $user, $email, $password) = $match;
    }