PHP explode() 函數
PHP explode() 是一個字符串函數,它通過一個字符串來分割另一個字符串。愛掏網 - it200.com簡單來說,它把一個字符串分割成一個數組。愛掏網 - it200.comexplode() 函數有一個 分隔符 參數,該參數不能包含空字符串,因為它保存了要分割的原始字符串。愛掏網 - it200.com它是一個二進制安全函數。愛掏網 - it200.com
explode() 函數通過分割原始字符串創建一個字符串數組。愛掏網 - it200.com
explode (string separator, stringoriginalString, int $limit)
參數
在explode()函數中有三個參數,其中兩個參數是必需的,最后一個參數是可選的。愛掏網 - it200.com這些參數如下:
$separator:
這個參數指定原始字符串分割的字符。愛掏網 - it200.com簡單來說,我們可以說,當在字符串中找到這個字符時,字符串將被分成幾部分。愛掏網 - it200.com
$originalString:
這個參數保存要分割成數組的字符串。愛掏網 - it200.com
$limit:
$limit
參數指定要返回的數組元素的數量。愛掏網 - it200.com它可以包含任何整數值(零、正數或負數)。愛掏網 - it200.com
$limit
的可能值:
正數 (大于0) | 如果此參數包含正數值,則該函數將返回一個字符串數組,拆分為$limit 參數定義的大小。愛掏網 - it200.com |
---|---|
負數 (小于0) | 如果$limit 參數包含負數值,則將刪除最后的元素,并返回剩余的元素。愛掏網 - it200.com |
零 | 如果$limit 參數為零(0),它將作為單個數組元素返回整個字符串。愛掏網 - it200.com |
注意:請記住,如果不在explode()函數中提供$limit
參數,則返回的數組將包含由$separator字符串分隔的字符串的所有元素。愛掏網 - it200.com
返回值
此函數返回一個 字符串數組 。愛掏網 - it200.com該字符串數組由分割原始字符串組成。愛掏網 - it200.com
更改
在 $limit 參數中,允許使用負值。愛掏網 - it200.com
示例
示例1: 帶有$limit參數的數組
<?php
// original string
Original_str = "Hello, we are here to help you.";
// Passed zero print_r (explode (" ",Original_str, 0));
// Passed positive value
print_r (explode (" ",Original_str, 4)); // Passed negative value print_r (explode (" ",Original_str, -3));
?>
輸出:
在上面的示例中,使用空格字符作為分隔符來分割字符串。愛掏網 - it200.com
Array ( [0] => Hello, we are here to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here )
上述輸出可以被視為更好地理解:
Array (
[0] => Hello, we are here to help you.
) Array (
[0] => Hello,
[1] => we
[2] => are
[3] => here to help you.
) Array (
[0] => Hello,
[1] => we
[2] => are
[3] => here
)
示例1: 沒有$limit參數的數組
<?php
// original string
Original_str = "Hello, welcome to javatpoint."; //without passing optional parameter
print_r (explode (" ",Original_str));
?>
輸出:
在上面的代碼中,我們沒有傳遞可選參數,即$limit。愛掏網 - it200.com因此,explode()函數將字符串拆分為不同索引的數組。愛掏網 - it200.com
Array ( [0] => Hello, [1] => welcome [2] => to [3] => javatpoint. )
示例 3:
<?php
// original string
Original_str = "Hello, welcome to javatpoint."; //without passing optional parameter
print_r (explode ("e",Original_str));
?>
輸出:
在上面的代碼中,我們使用“ e ”字符來將字符串分割成數組。愛掏網 - it200.com所以,無論在哪里找到“ e ”,字符串都會被分割。愛掏網 - it200.com
Array ( [0] => H [1] => llo, w [2] => lcom [3] => to javatpoint. )