Current Location: Home> Latest Articles> hexdec cooperates with substr to process hexadecimal values ​​in strings

hexdec cooperates with substr to process hexadecimal values ​​in strings

gitbox 2025-05-27

1. Introduction to hexdec function

hexdec is a PHP built-in function that converts hex strings into decimal integers.

 int hexdec ( string $hex_string )

For example:

 echo hexdec("1A"); // Output 26

2. Introduction to substr function

substr is used to intercept substrings of specified positions and lengths in strings.

 string substr ( string $string , int $start [, int $length ] )

For example:

 echo substr("abcdef", 1, 3); // Output "bcd"

3. Comprehensive application examples

Suppose we have a string containing several hexadecimal numbers mixed with other characters, such as:

 $data = "id=abc1234fxyz";

Our goal is to extract the "1234f" part from this string (assuming its position is known) and convert it to a decimal number.

The implementation method is as follows:

 <?php
$data = "id=abc1234fxyz";

// From the string6Start with characters,Intercept5Characters(Right now "1234f")
$hexString = substr($data, 5, 5);

// 将Intercept的Hexadecimal string转换为十进制数字
$decimalValue = hexdec($hexString);

echo "Hexadecimal string: " . $hexString . "\n";
echo "Converted decimal values: " . $decimalValue . "\n";
?>

Output:

 Hexadecimal string: 1234f
Converted decimal values: 74575

4. Extract hexadecimal string from uncertain locations

If the hexadecimal string is not in a fixed position, you can use the string search function strpos to locate it, and then intercept it with substr .

For example:

 <?php
$data = "user=xyz&code=1a2b3c&status=ok";

// turn up "code=" Position in string
$pos = strpos($data, "code=");

if ($pos !== false) {
    // "code=" The starting position of the hexadecimal number
    $start = $pos + strlen("code=");

    // Assume that the length of the hexadecimal number is6
    $hexString = substr($data, $start, 6);

    $decimalValue = hexdec($hexString);

    echo "提取的Hexadecimal string: " . $hexString . "\n";
    echo "Converted decimal values: " . $decimalValue . "\n";
} else {
    echo "未turn up指定的Hexadecimal string。\n";
}
?>

Output:

 提取的Hexadecimal string: 1a2b3c
Converted decimal values: 1715004

5. Summary

  • substr is used to intercept the specified part of the string.

  • hexdec converts a hex string to a decimal value.

  • The combination of the two makes it easy to extract and convert hexadecimal numbers embedded in a string.