Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Cách tách chữ và số thành hai mảng từ chuỗi trong PHP

Dùng preg_split() kết hợp array_shift() và array_pop(). Giả sử chuỗi chữ và số:

$values = "5j4o5h8n";

Muốn tách số và chữ thành mảng riêng.

Ví dụ

<!DOCTYPE html> <html> <body> <?php 
$values = "5j4o5h8n";
$singleValues = preg_split("/\d+/", $values);
array_shift($singleValues);
print_r($singleValues);
$resultNumber = preg_split("/[a-z]+/", $values);
array_pop($resultNumber);
print_r($resultNumber);
?> </body> </html>

Kết quả

Array ( [0] => j [1] => o [2] => h [3] => n )
Array ( [0] => 5 [1] => 4 [2] => 5 [3] => 8 )