PHP.mk документација

sscanf

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.sscanf.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.sscanf.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
sscanf

Референца за `function.sscanf.php` со подобрена типографија и навигација.

function.sscanf.php

sscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

sscanfParses input from a string according to a format

= NULL

sscanf(string $string, string $format, mixed &...$vars): array|int|null

Функцијата sscanf() is the input analog of printf(). sscanf() reads from the string string and interprets it according to the specified format.

Any whitespace in the format string matches any whitespace in the input string. This means that even a tab (\t) in the format string can match a single space character in the input string.

Параметри

string

чии вредности се измешани. string being parsed.

format

The interpreted format for string, which is described in the documentation for sprintf() with following differences:

  • Function is not locale-aware.
  • F, g, G and b are not supported.
  • D stands for decimal number.
  • i stands for integer with base detection.
  • n stands for number of characters processed so far.
  • s stops reading at any whitespace character.
  • * наместо argnum$ suppresses the assignment of this conversion specification.
vars

Optionally pass in variables by reference that will contain the parsed values.

Вратени вредности

If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Ако на оваа функција ѝ биле предадени само два параметри, вредностите што се анализираат ќе бидат вратени како низа. Во спротивно, ако се предадат опционални параметри, функцијата ќе го врати бројот на доделени вредности. Опционалните параметри мора да се предадат преку референца. format Ако има повеќе поднизи што се очекуваат во string, null ќе биде вратено.

Примери

Пример #1 sscanf() Пример

<?php
// getting the serial number
list($serial) = sscanf("SN/2350001", "SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list(
$month, $day, $year) = sscanf($mandate, "%s %d %d");
echo
"Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
?>

отколку што се достапни во

Пример #2 sscanf() Ако се поминат опционални параметри, функцијата ќе го врати бројот на доделени вредности.

<?php
// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo
"<author id='$id'>
<firstname>
$first</firstname>
<surname>
$last</surname>
</author>\n"
;
?>

Види Исто така

  • printf() Излез на стринг
  • sprintf() - Врати форматирана низа
  • fprintf() - Запиши форматирана низа во поток
  • vprintf() Излез на стринг
  • vsprintf() - Врати форматирана низа
  • vfprintf() - Запиши форматирана низа во поток
  • fscanf() - Парсира влез од датотека според формат
  • number_format() - Заокружи дропки надолу
  • date() - Форматирај Unix временски печат

Белешки од корисници 16 белешки

- користење опционални параметри
пред 23 години
this function is a great way to get integer rgb values from the html equivalent hex.

list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');
jon на fuck точка org
figroc at gmail dot com
After playing around with this for a while, I found that if you use %[^[]] instead of %s (since php has problems with spaces when using %s) it works nicely. 

For those that aren't familiar with regular expressions, %[^[]] basically matches anything that isn't nothing.

Hope this helps. - Gabe
mikewillitsgmail.com
пред 18 години
FYI - if you are trying to scan from a string which contains a filename with extension. For instance:

<?php

$out = sscanf('file_name.gif', 'file_%s.%s', $fpart1, $fpart2);

?>

The scanned string in the $fpart1 parameter turns out to be 'name.gif' and $fpart2 will be NULL.

To get around this you can simply replace the "." with a space or another "white-space like" string sequence.

I didn't see any other comments on regarding string literals which contain a '.' so I thought I'd mention it. The subtle characteristics of having "white-space delimited" content I think can be a source of usage contention. Obviously, another way to go is regular expressions in this instance, but for newer users this may be helpful.

Just in case someone else spent 10 minutes of frustration like I did. This was seen on PHP Version 5.2.3-1ubuntu6.3.

Searching the bug reports shows another users misunderstanding: http://bugs.php.net/bug.php?id=7793
elgabos на umail точка ucsb точка edu
20 години пред
The %[^[]]-trick may seem to work, but it doesn't!

What happens is that sscanf will simply match any characters but an opening square bracket (which is rather rare and that's why it might just seem to work).
But even worse it will expect a ]-character next and continue to match anything.

Now what you can do is make sscanf look for any character but a character that is really never used... a good choice is the linebreak "%[^\\n]", especially in combination with fscanf.

What you can also do is copy and paste any unused ascii character like #001 or something.
leg
пред 17 години
@mikewillitsgmail.com:

<?php

$out = sscanf('file_name.gif', 'file_%[^.].%s', $fpart1, $fpart2);

echo '<pre>';
print_r($fpart1);
echo '<hr />';
print_r($fpart2);
echo '</pre>';

?>

output:

name
-
gif

The "^." part avoid the first searched string to be too greedy. But doesn't protect you against an "file_test.name.gif" input, with bad results!
anonymouse
19 години пред
I've seen several examples of people using brackets to define what look like regexp character classes. In my limited testing I don't think they are genuine character classes but they seem to be similar.

My task was to use sscanf() to parse an array of strings with the format:

number SPACE string_which_may_also_have_spaces

The normal %s conversion command treats spaces as some kind of delimiter. So, you can get the strings if you know beforehand how many "words" there will be. But, my input was variable.

Here's what I came up with: (note use of the dollar-sign 'end of string' hidden delimiter)

sscanf($string_to_parse,'%d %[^$]s',$num,$text);

This conversion command says "look for an integer, then a space, then any string up to the end of the string"
Виктор
пред 13 години
One thing to note: unlike C/C++, a variable %n is assigned to will be counted in the return value.
Brainiac361
21 години пред
Security Note:

Although it is a very powerful technique, keep in mind that it is easily deceived.

Many successful exploits have been based on scanf attacks.  It should not be used on untrusted input without a lot of additional validation.
skeltoac
20 години пред
To parse a line from an Apache access log in common format:

<?php
$log = array();
$n = sscanf(trim($line), '%s %s %s [%[^]]] "%s %s %[^"]" %d %s "%[^"]" "%[^"]"',
    $log['ip'],
    $log['client'],
    $log['user'],
    $log['time'],
    $log['method'],
    $log['uri'],
    $log['prot'],
    $log['code'],
    $log['bytes'],
    $log['ref'],
    $log['agent']
);
?>
codeslinger на compsalot точка com
20 години пред
If you just wants filter out information between two parts of a string, i used the following, it works better for me then the sscanf function. 

<?php
function scanstr($zoekstr,$part1,$part2) {
$firstpos=strpos ($zoekstr, $part1)+strlen($part1);
$lastpos=strpos ($zoekstr, $part2);
$scanresult=substr ($zoekstr, $firstpos, $lastpos-$firstpos);
    return($scanresult);
}
echo scanstr ("var1=hello&var2=test&var3=more","var2=","&var3");
?>
Vincent Jansen
figroc at gmail dot com
apparently, sscanf always splits at spaces, even if spaces are not specified in the format. consider this script:

<?php
$str = "This is a\tsentence with\ttabs";
$scanned = sscanf($str, "%s\t%s\t%s");
echo join(" : ", $scanned);
?>

this echoes "This : is : a", not the expected "This is a : sentence with : tabs."
this behaviour is fine if your strings don't contain spaces, but if they do you'd be better off using explode().
narainsbrain на yahoo точка com
пред 5 години
It should also be noted that when used with sscanf both x and X produce the same output (i.e. they are case-insensitive).

<?php
var_dump(sscanf("0xdead|0XDEAD", "%X|%x")); // works
Philo
20 години пред
added country code (1) to phone number function:

function formatPhone($phone) {
       if (empty($phone)) return "";
       if (strlen($phone) == 7)
               sscanf($phone, "%3s%4s", $prefix, $exchange);
       else if (strlen($phone) == 10)
               sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
       else if (strlen($phone) > 10)
               if(substr($phone,0,1)=='1') {
                                 sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
                             }
                             else{
                                 sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
                                }
       else
               return "unknown phone format: $phone";
       $out = "";
       $out .= isset($country) ? $country.' ' : '';
       $out .= isset($area) ? '(' . $area . ') ' : '';
       $out .= $prefix . '-' . $exchange;
       $out .= isset($extension) ? ' x' . $extension : '';
       return $out;
}
joshmckenneyATgmailDOT(0{
yasuo_ohgaki at hotmail dot com
Actually sscanf()_always_ returns an array if you specify less return variables than format specifiers. i may change this to return a scalar if only a single format specifier exists.
  Note that sscanf() is (almost) the complete functional equivalent of its "C" counterpart, so you can do the following to get the expected effect :

   sscanf("SN/2350001","SN/%d",&$serial)

The array return was a nicety for PHP.
clcollie на mindspring точка com
пред 23 години
In PHP >= 4.3.0, if you use additional reference parameters, you will get this warning:

PHP Warning:  Call-time pass-by-reference has been deprecated - argument passed by value

This clearly has the potential to cause unexpected consequences (vars left empty), and will break existing code. So don't do it! These docs need updating to say this too.

The syntax:

    list($a, $b) = sscanf("hello world", "%s %s");

will work as expected, and doesn't seem to cause any problems with Apache that I've noticed.
marcus на synchromedia точка co точка uk
пред 23 години
More fun with phones!  This assumes that the phone number is 10 digits, with only numeric data, but it would be easy to check the length of the string first.

function formatPhone($phone) {
        if (empty($phone)) return "";
        sscanf($phone, "%3d%3d%4d", $area, $prefix, $exchange);
        $out = @$area ? "($area) " : "";
        $out .= $prefix . '-' . $exchange;
        return $out;
}
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.