Hướng dẫn
Quảng cáo

Hàm strcspn() trong PHP

Hướng dẫn cách sử dụng hàm strcspn() trong lập trình PHP

Tác dụng của hàm strcspn()

The strcspn() function returns the number of characters present in a string (including whitespaces) before any part of mask (list of disallowed characters) is found.

The following table summarizes the technical details of this function.

Return Value: Returns the length of the initial portion of string that does not contain any characters specified in the mask.
Version: PHP 4+

Syntax

The basic syntax of the strcspn() function is given with:

strcspn(string, mask, start, length);

The following example shows the strcspn() function in action.

<?php
// Sample string
$str = "Hello World!";

// Defining mask
$mask = "W";

// Find length of initial portion of string not matching mask
echo strcspn($str, $mask);
?>

Parameters

The strcspn() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to work on.
mask Required. Specifies the string containing every disallowed character.
start Optional. Specifies the position in the string to start searching.
length Optional. Specifies the portion of the string to search.

More Examples

Here're some more examples showing how strcspn() function actually works:

The following example returns the length of the initial portion of string that doesn't contains the characters "l" and "o". Let's try it out and see how it works:

<?php
echo strcspn("Hello World!", "lo");
?>

In the following example only the portion "World" of the string will be examined, because the position to start searching is 6 and the length of the string to search is 5.

<?php
echo strcspn("Hello World!", "o", 6, 5);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements