Understanding PHP strcspan() Function: Syntax, Usage, and Examples
This article explains PHP's strcspan() function, detailing its syntax, parameters, return value, and provides three practical code examples that demonstrate how it counts consecutive characters in a string based on a given character list.
PHP is a widely used server‑side scripting language for developing dynamic web pages and applications. Among its many built‑in string functions, strcspan() is particularly useful for counting the number of consecutive characters in a string that belong to a specified character list.
The strcspan() function takes two arguments—the input string and a character list string—and scans the input from the beginning until it encounters a character not present in the list, returning the count of consecutive allowed characters.
Syntax of strcspan()
<code>int strcspan ( string $str, string $charlist )</code>$str is the string to be examined, and $charlist contains all characters that are allowed (it can be a range like "a‑z" or an explicit set like "abc"). The function returns an integer representing the length of the initial segment of $str that consists only of characters from $charlist .
Usage of strcspan()
Example 1:
<code>$str = "Hello World!";
$charlist = "HeloWrd";
$length = strcspan($str, $charlist);
echo $length;</code>Output: 5
In this example, the allowed characters are H, e, l, o, W, r, d. The function counts the initial segment "Hello" before encountering a space, so it returns 5.
Example 2:
<code>$str = "abc123def456";
$charlist = "a-z";
$length = strcspan($str, $charlist);
echo $length;</code>Output: 3
Here the character list is the lowercase alphabet. The function counts the initial "abc" before hitting the digit "1", returning 3.
Example 3:
<code>$str = "1234567890";
$charlist = "0-9";
$length = strcspan($str, $charlist);
echo $length;</code>Output: 10
This example allows all digits, so the function counts the entire string "1234567890" and returns 10.
The strcspan() function is useful for validating user input, checking whether a string contains only permitted characters, and can be flexibly applied to various string‑processing tasks.
Summary
This article detailed the PHP strcspan() function, its syntax, parameters, and return value, and illustrated its behavior with three concrete examples covering alphabetic, alphanumeric, and numeric character sets.
PHP Learning Recommendations
Vue3+Laravel8+Uniapp Beginner to Practical Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Master Course
Workerman+TP6 Real‑time Chat System Limited‑time Offer
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.