2012-05-14 31 views
6

Chúng ta có thể thực hiện nhiều phát nổ() trong PHP không?Chúng ta có thể thực hiện nhiều câu lệnh phát nổ trên một dòng trong PHP không?

Ví dụ, để làm điều này:

foreach(explode(" ",$sms['sms_text']) as $no) 
foreach(explode("&",$sms['sms_text']) as $no) 
foreach(explode(",",$sms['sms_text']) as $no) 

Tất cả trong một nổ như thế này:

foreach(explode('','&',',',$sms['sms_text']) as $no) 

cách tốt nhất để làm điều này là gì? Những gì tôi muốn là để chia chuỗi trên nhiều delimiters trong một dòng.

Trả lời

15

Nếu bạn đang tìm kiếm để chia chuỗi với nhiều delimiters, có lẽ preg_split sẽ là thích hợp.

$parts = preg_split('/(\s|&|,)/', 'This and&this and,this'); 
print_r($parts); 

mà kết quả trong:

Array ( 
    [0] => This 
    [1] => and 
    [2] => this 
    [3] => and 
    [4] => this 
) 
+0

hi thanks cho mã nhưng tôi có \ r \ n \ giá trị và không gian để có được nổ của nó foreach không làm việc (preg_split ('/ (\ r \ n \ s | & |,)/', $ sms [' sms_text ']) là $ no) – Harinder

+0

thankx bro giải quyết foreach (preg_split ("/ \ r \ n | (\ s | & |,) /", $ sms ['sms_text']) là $ no) – Harinder

2

bạn có thể sử dụng

function multipleExplode($delimiters = array(), $string = ''){ 

    $mainDelim=$delimiters[count($delimiters)-1]; // dernier 

    array_pop($delimiters); 

    foreach($delimiters as $delimiter){ 

     $string= str_replace($delimiter, $mainDelim, $string); 

    } 

    $result= explode($mainDelim, $string); 
    return $result; 

} 
0

Bạn có thể sử dụng preg_split() function để stplit một chuỗi sử dụng một biểu thức chính quy, như vậy:

$text = preg_split('/(|,|&)/', $text); 
0

Tôi muốn đi với strtok(), ví dụ:

$delimiter = ' &,'; 
$token = strtok($sms['sms_text'], $delimiter); 

while ($token !== false) { 
    echo $token . "\n"; 
    $token = strtok($delimiter); 
} 
4

Đây là một giải pháp tuyệt vời Tôi tìm thấy tại PHP.net:

<?php 

//$delimiters must be an array. 

function multiexplode ($delimiters,$string) { 

    $ready = str_replace($delimiters, $delimiters[0], $string); 
    $launch = explode($delimiters[0], $ready); 
    return $launch; 
} 

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)"; 
$exploded = multiexplode(array(",",".","|",":"),$text); 

print_r($exploded); 

//And output will be like this: 
// Array 
// (
// [0] => here is a sample 
// [1] => this text 
// [2] => and this will be exploded 
// [3] => this also 
// [4] => this one too 
// [5] =>) 
//) 

?> 
Các vấn đề liên quan