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

Hàm substr() trong PHP

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

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

The substr() function extracts a part of a string.

The following table summarizes the technical details of this function.

Return Value: Returns the extracted part of string; or FALSE on failure, or an empty string.
Changelog: Since PHP 7.0, if start is equal to the string length, this function returns an empty string (""). In earlier versions it returns FALSE.
Version: PHP 4+

Syntax

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

substr(string, start, length);

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

<?php
// Sample string
$str = "Alice in Wonderland";

// Getting substring
echo substr($str, 0, 5);
?>

Tip: The string positions start at 0, not 1. For instance, in the string "lemon", the character at position 0 is "l", the character at position 1 is "e", and so forth.

Note: If start is greater than the string length, FALSE will be returned. Also, if length parameter is omitted, the substring starting from start until the end of the string will be returned.


Parameters

The substr() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to work on.
start

Required. Specifies the position in the string from where the extraction begins.

  • If start is a positive number, the returned string will start at the start'th position in string, counting from zero.
  • If start is a negative number, the returned string will start at the start'th character from the end of string.
  • If string is less than start characters long, FALSE will be returned.
length

Optional. Specifies how many characters to extract.

  • If length is a positive number, the string returned will contain at most length characters beginning from string (depending on the length of string).
  • If length is a negative number, then that many characters will be left out from the end of string (after the start position has been calculated when a start is negative).
  • If length is is 0, FALSE or NULL, an empty string will be returned.

More Examples

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

The following example demonstrates the usage of positive and negative start parameter.

<?php
// Sample string
$str = "Alice in Wonderland";

// Getting substrings
echo substr($str, 9)."<br>";
echo substr($str, 6, 2)."<br>";
echo substr($str, -4)."<br>";
echo substr($str, -10, 6);
?>

The following example demonstrates the usage of positive and negative length parameter.

<?php
// Sample string
$str = "Alice in Wonderland";

// Getting substrings
echo substr($str, 2, 3)."<br>";
echo substr($str, 9, -4)."<br>";
echo substr($str, -13, 2)."<br>";
echo substr($str, -10, -7);
?>

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

Bài viết mới

Advertisements