1. Định nghĩa
- Hàm explode trong PHP cho phép bạn chuyển một chuỗi sang một mảng dựa trên các ký tự phân cách. Trong thực tế, xử lý chuỗi là rất cần thiết và sử dụng khá thường xuyên, ví dụ khi bạn muốn tách họ và tên của một người dùng, tách từng từ khóa trong một danh sách từ khóa có phân cách bằng một ký tự nào đó…
2. Cú pháp
3. Tham sốMã nguồn PHP:explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
- $separator : ký tự hoặc chuỗi ký tự dùng để phân tách các phần tử trong chuỗi
- $string : chuỗi cần tách thành mảng
- $limit : tham số tùy chọn. Giới hạn số lượng phần tử trả về trong mảng:
+ nếu $limit > 0: trả về mảng có số phần tử là limit phần tử ở đầu chuỗi
+ nếu $limit < 0: trả về mảng có số phần tử đã loại bỏ $limit phần tử ở cuối chuỗi
+ nếu $limit = 0: trả về mảng với 1 phần tử
4. Kết quả trả về
- String[] array : Trả về một mảng các chuỗi con
5. Ví dụ:
- Ví dụ 1: Sử dụng tham số $limit để trả về số lượng các phần tử của mảng:
+ input:
+ output:Mã nguồn PHP:<?php
$str = 'one,two,three,four,five,six';
// default
print_r(explode(',', $str));
print "<br>";
// zero limit
print_r(explode(',', $str, 0));
print "<br>";
// positive limit
print_r(explode(',', $str, 2));
print "<br>";
// negative limit
print_r(explode(',', $str, -2));
?>
- Example #1 explode() examples:Mã nguồn PHP:Array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six )
Array ( [0] => one,two,three,four,five,six )
Array ( [0] => one [1] => two,three,four,five,six )
Array ( [0] => one [1] => two [2] => three [3] => four )
- Example #2 explode() return examples:Mã nguồn PHP:<?php
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
?>
+ input:
+ output:Mã nguồn PHP:<?php
/*
A string that doesn't contain the delimiter will simply
return a one-length array of the original string.
*/
$input1 = "hello";
$input2 = "hello,there";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );
?>
- Example #3 limit parameter examples:Mã nguồn PHP:array(1)
(
[0] => string(5) "hello"
)
array(2)
(
[0] => string(5) "hello"
[1] => string(5) "there"
)
array(2)
(
[0] => string(0) ""
[1] => string(0) ""
)
+ input:
+ output:Mã nguồn PHP:<?php
$str = 'one|two|three|four';
// positive limit
print_r(explode('|', $str, 2));
// negative limit
print_r(explode('|', $str, -1));
?>
6. Tài liệu tham khảoMã nguồn PHP:Array
(
[0] => one
[1] => two|three|four
)
Array
(
[0] => one
[1] => two
[2] => three
)
https://www.php.net/manual/en/function.explode.php
https://www.w3schools.com/php/func_string_explode.asp
https://topdev.vn/blog/ham-explode-trong-php/



LinkBack URL
About LinkBacks








Trả lời kèm Trích dẫn
