I can not find a function to check.

# пример function getBin($data) { return pack('H*', $data); } 

When transmitting a non-hexadecimal number, I get the error:
Warning: pack(): Type H: illegal hex digit o
Warning: pack(): Type H: illegal hex digit h

Can I somehow check or just ignore the errors: @pack('H*', $data) ?

  • Translate a string into upper / lower case and check that each character is a string from a HEX alphabet. Three lines of code, drag. - Vladimir Martyanov

2 answers 2

There is such a function

 function getBin($data) { if (ctype_xdigit($data)) { return pack('H*', $data); } else { return 0; } } 

    several options at once:

    file mixhex.php (php):

     <?php # 1 Вариант с указанием строки $str = "AB10BC99"; if (!preg_match('/^[0-9A-Fa-f]$/', $str)) { echo "String $str is not HEX\n"; } # 2 Вариант строки в массиве $strings = array('AB10BC99', 'AR1012', 'ab12bc99'); foreach ($strings as $testcase) { if (ctype_xdigit($testcase)) { echo "String $testcase all are hexadecimal digits.\n"; } else { echo "String $testcase not all are hexadecimal digits.\n"; } } # 3 Вариант чтения строк в массив из файла (т.к. файл заканчивается пустой строкой то плследний результат будет пустой) $lines = file('mixhex_in'); foreach ($lines as $line_num => $line) { echo "Строка #{$line_num} : " .($line) . "\n"; if (ctype_xdigit($line)) { echo "The string $line consists of all hexadecimal digits.\n"; } else { echo "The string $line does not consist of all hexadecimal` `digits.\n"; } } ?> 

    running script mixhex.php:

     php -f mixhex.php 

    file mixhex_in (input lines):

     AB10BC99 AR1012 ab12bc99 

    checked on debian 8 64 bit.

    • @Plush and a request to all: check the answer, it will also come in handy for me (so as not to raise similar questions here). - user197988 2:32 pm