PHP: function strtoul


We know function strtoul in C++: converts the string into an unsigned long int according to the base of the number

unsigned long int strtoul ( const char * str, char ** endptr, int base );

Convert string to unsigned long integer
Parses the C string str interpreting its content as an integral number of the specified base, which is returned as an unsigned long int value.

This function operates like strtol to interpret the string, but produces numbers of type unsigned long int.

<?php

/**
 * @author www.tutorialspots.com
 * @copyright 2013
 */

function strtoul($str, &$end = '', $base = 10)
{
    $end = $str;
    if (!is_int($base) || $base > 36 || $base < 2)
        return 0;

    $chars = "0123456789abcdefghijklmnopqrstuvwxyz";
    $chars = substr($chars, 0, $base);

    $num = strspn($str, $chars);

    if ($num == 0)
        return 0;

    $first_str = substr($str, 0, $num);
    $end = substr($str, $num, strlen($str)-$num);
    return base_convert($first_str, $base, 10);
}

?>

Example:

$z = strtoul('012www.tutorialspots.com',$end);

var_dump($z, $end);

Result:
string(2) "12"
string(21) "www.tutorialspots.com"

Leave a Reply