伍佰目录 短网址
  当前位置:海洋目录网 » 站长资讯 » 站长资讯 » 文章详细 订阅RssFeed

PHP - Manual: sscanf

来源:网络转载 浏览:46次 时间:2023-06-17
str_contains » « sprintf PHP 手册 函数参考 文本处理 字符串 字符串 函数

sscanf

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

sscanf — 根据指定格式解析输入的字符

说明

sscanf(string $str, string $format, mixed &$... = ?): mixed

这个函数 sscanf() 输入类似 printf()。 sscanf() 读取字符串str 然后根据指定格式format解析, 格式的描述文档见 sprintf()。

指定的格式字符串中的任意空白匹配输入字符串的任意空白.也就是说即使是格式字符串中的一个制表符 \t 也能匹配输入 字符串中的一个单一空格字符

参数

str

将要被解析的 字符串.

format

The interpreted format for 解析str的格式, 除了以下不同外,其余的见 sprintf()的描述文档:

函数不区分语言地区 F, g, Gb 不被支持. D 表示十进制数字. i stands for integer with base detection. n 代表目前已经处理的字符数。 s 遇到任意空格字符时停止读取。 ...

可以选参数将以引用方式传入,它们的值将被设置为解析匹配的值

返回值

如果仅传入了两个参数给这个函数,解析后将返回一个数组,否则,如果可选参数被传入,这个函数将返回被设置了值的个数

如果format存在的子字符串比 str内可用的多, -1 将被返回.

范例

示例 #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";
?>

If optional parameters are passed, the function will return the number of assigned values.

示例 #2 sscanf() - using optional parameters

<?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";
?>

参见

fscanf() - 从文件中格式化输入 printf() - 输出格式化字符串 sprintf() - 返回格式化字符串
add a note

User Contributed Notes 18 notes

up down 66 jon at fuck dot org19 years ago 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');
up down 10 elgabos at umail dot ucsb dot edu20 years ago 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
up down 14 mikewillitsgmail.com14 years ago 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
up down 4 Brainiac36116 years ago 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.
up down 3 codeslinger at compsalot dot com17 years ago 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.
up down 3 Vincent Jansen17 years ago 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");
?>
up down 3 skeltoac16 years ago 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']
);
?>
up down 4 leg13 years ago @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!
up down 1 anonymouse15 years ago 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"
up down 1 Victor9 years ago One thing to note: unlike C/C++, a variable %n is assigned to will be counted in the return value. up down 0 Philo1 year ago 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
up down 0 narainsbrain at yahoo dot com20 years ago 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().
up down -1 joshmckenneyATgmailDOT(0{16 years ago 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;
}
up down -2 clcollie at mindspring dot com21 years ago 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.
up down -4 sbarnum.pointsystems@com19 years ago 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;
}
up down -3 marcus at synchromedia dot co dot uk19 years ago 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.
up down -9 nmmm at nmmm dot nu10 years ago This is more like C/C++ example, but works on PHP too.

<?php
$qs = "index.php?id=34&name=john";

print_r(   sscanf($qs, "%[^?]?%[^?]")   );

$qs = "id=34&name=john";

print_r(   sscanf($qs, "id=%[^&]&name=%[^&]")   );
?>
up down -10 Igor Feghali13 years ago parses an input string with fixed field sizes that contains data with spaces:

<?php
$result = sscanf("  Vendor: My Vendo Model: Super Model Foo  Rev: 1234", 
                 '  Vendor: %8[ -~] Model: %16[ -~] Rev: %4c',
                 $vendor, $model, $rev);
?>

$vendor => My Vendo
$model => Super Model Foo
$rev => 1234
add a note

官方地址:https://www.php.net/manual/en/function.sscanf.php

  推荐站点

  • At-lib分类目录At-lib分类目录

    At-lib网站分类目录汇集全国所有高质量网站,是中国权威的中文网站分类目录,给站长提供免费网址目录提交收录和推荐最新最全的优秀网站大全是名站导航之家

    www.at-lib.cn
  • 中国链接目录中国链接目录

    中国链接目录简称链接目录,是收录优秀网站和淘宝网店的网站分类目录,为您提供优质的网址导航服务,也是网店进行收录推广,站长免费推广网站、加快百度收录、增加友情链接和网站外链的平台。

    www.cnlink.org
  • 35目录网35目录网

    35目录免费收录各类优秀网站,全力打造互动式网站目录,提供网站分类目录检索,关键字搜索功能。欢迎您向35目录推荐、提交优秀网站。

    www.35mulu.com
  • 就要爱网站目录就要爱网站目录

    就要爱网站目录,按主题和类别列出网站。所有提交的网站都经过人工审查,确保质量和无垃圾邮件的结果。

    www.912219.com
  • 伍佰目录伍佰目录

    伍佰网站目录免费收录各类优秀网站,全力打造互动式网站目录,提供网站分类目录检索,关键字搜索功能。欢迎您向伍佰目录推荐、提交优秀网站。

    www.wbwb.net