strspn 有什么意义?

问题描述 投票:0回答:6

今天在工作中,我们试图找出您会使用 strspn 的任何理由。

我搜索了谷歌代码,看看它是否曾经以有用的方式实现过,但结果却是空白。我只是无法想象我真的需要知道仅包含另一个字符串中的字符的字符串的第一段的长度的情况。有什么想法吗?

php function built-in
6个回答
4
投票

虽然您链接到 PHP 手册,但

strspn()
函数来自 C 库,以及
strlen()
strcpy()
strcmp()
等。

strspn()
是一种方便的替代方法,可以替代逐个字符地挑选字符串,测试这些字符是否与一组值中的一个匹配。在编写标记器时它很有用。
strspn()
的替代方案是大量重复且容易出错的代码,如下所示:

for (p = stringbuf; *p; p++) {
  if (*p == 'a' || *p == 'b' || *p = 'c' ... || *p == 'z') {
    /* still parsing current token */
  }
}

你能发现错误吗? :-)

当然,在内置支持正则表达式匹配的语言中,

strspn()
没有什么意义。但是当用 C 语言编写 DSL 的基本解析器时,它非常漂亮。


1
投票

它基于 ANSI C 函数

strspn()
。它在没有高级字符串类的低级 C 解析代码中很有用。它在 PHP 中的用处要小得多,因为 PHP 有很多有用的字符串解析函数。


1
投票

嗯,根据我的理解,它与这个正则表达式是一样的:

^[set]*

其中set是包含要查找的字符的字符串。

您可以使用它来搜索字符串开头的任何数字或文本并进行分割。

看起来在将代码移植到 php 时会很有用。


1
投票

我认为它非常适合列入黑名单并让用户知道错误从哪里开始。就像 MySQL 从发生错误的地方返回部分查询一样。

请查看此功能,它可以让用户知道他的评论的哪一部分无效:

function blacklistChars($yourComment){

$blacklistedChars = "!@#$%^&*()";
$validLength = strcspn($yourComment, $blacklistedChars);
if ($validLength !== strlen($yourComment))
{

    $error = "Your comment contains invalid chars starting from here: `" . 
        substr($yourComment, (int) '-' . $validLength) . "`";

    return $error;
}

return false;
}

$yourComment = "Hello, why can you not type and $ dollar sign in the text?"; 
$yourCommentError = blacklistChars($yourComment);

if ($yourCommentError <> false)
echo $yourCommentError;

0
投票

它对于像 atoi 这样的函数特别有用 - 你有一个想要转换为数字的字符串,并且你不想处理任何不在集合“-.0123456789”中的东西

但是,它的用途有限。

-亚当


0
投票

您可以使用它来捕获初始缩进,例如,规范化 Markdown 或 YAML 字符串:

<?php

$content = <<<TEXT
    aaa
    aaa
        aaa
        aaa
    aaa
    aaa
TEXT;

$dent = strspn($content, ' ');

if ($dent > 0) {
    // Remove the first indent
    $content = substr($content, $dent);
    // Remove other indent(s) after the first line
    $content = strtr($content, ["\n" . str_repeat(' ', $dent) => "\n"]);
}

echo $content;
© www.soinside.com 2019 - 2024. All rights reserved.