Jump to: navigation, search

Php sscanf

From w3cyberlearnings

Contents

PHP function sscanf

This function parses input string to variable base on a specific format.

Syntax sscanf

  • string: string input
  • format: format string
  • arg1: for the first variable to store data
  • arg2: for the second variable to store data
  • arg++: for the third,fourth, and so on, to store data
sscanf(string,format,arg1,arg2,arg++)

format

  •  % - returns a percent sign.
  • b - is an integer and display it as a binary number.
  • c - is an integer and display it as a ASCII value.
  • d - is an integer and display as a signed decimal number.
  • e - is scientific notation with lowercase letter e(e.g. 1.2e+2).
  • E - is scientific notation with capital letter E(e.g.1.2E+2).
  • u - is an integer, and display as an unsigned decimal number.
  • f- is a float, and display as a floating-point number. (local aware)
  • F - is a float, and display as a floating-point number (non-locale aware).
  • g - is shorter of %e and %f.
  • G - is shorter of %E and %f.
  • o - is an integer, and display as an octal number.
  • s - is string and display as a string.
  • x - is an integer and display as a hexadecimal number (with lowercase letters).
  • X - is an integer and display as a hexadecimal number (with uppercase letters).
  • + - force (+) sign for positive number, and (-) for negative number.
  • ' - padding: %'x20s (uses 'x' as padding), %'u20x (uses 'u' as padding)
  • - - Left justified variable value
  • [0-9] - the minimum width specifies to the width of the variable value.
  • .[0-9] - set the decimal digits or maximum of the string width.

Example 1

<?php

$string = "name:johny age:30 address:Houston Tx";
sscanf($string, "name:%s age:%d address:%s", $name, $age, $address);
var_dump($name, $age, $address);
?>

Output

string(5) "johny" int(30) string(7) "Houston"

Example 2

<?php

$str = "I am 23 year old";
$str_aa = sscanf($str, "%s %s %d %s %s");
print_r($str_aa);
?>


Output

Array
(
    [0] => I
    [1] => am
    [2] => 23
    [3] => year
    [4] => old
)

Related Functions


Navigation
Web
SQL
MISC
References