2014-06-11 30 views
0

我返回內容輸入到由換行符分隔文本區域,像這樣後才返回非空數組值:需要使preg_split

06/10/2014 
06/11/2014 

不過,我想避免的事實,如果用戶應該以這種方式在文本框中輸入它(太多休息留下一個空的空間):

06/10/2014 


06/11/2014 

我想解釋的是,但仍然只返回兩個日期值,而不是額外的換行符。該陣列是這樣的,如果返回第二個例子:

PHP代碼

$date_array = preg_split("/(\r\n|\r|\n)/", $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY); 
      // check for any extra returns or white spaces 
      print_r($date_array); 

ARRAY

Array ([0] => 06/11/2014 
[1] => 
[2] => 06/12/2014) 

我想擺脫空數組,但array_filter不起作用。有什麼建議麼?謝謝!

+1

很棒的php.net手冊:'PREG_SPLIT_NO_EMPTY'也許吧? – AbraCadaver

+0

也試過了!沒有運氣,但好主意。 – jflay

+1

真的嗎? http://sandbox.onlinephpfunctions.com/code/ee25102e3a78fa845e823aee214e974994a1fc09 – AbraCadaver

回答

0

preg_split()\r\n pattern可用於解決您的問題。

$date_array = preg_split('/[\r\n]+/', $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY); 
+0

非常感謝您的回答,但由於質量問題,該評論已發佈供審閱。雖然你的回答可能是正確的,但沒有解釋爲什麼,以及OP做錯了什麼。雖然代碼只回答一般是不鼓勵的,但我不會推薦刪除它,因爲它似乎有幫助。 –

+0

@EngineerDollery,謝謝你指出我的錯誤。無論如何,我有一個更新的答案。 :) – fortune

+0

你的正則表達式模式是什麼? – jflay

1

只需使用array_filter這樣擺脫空數組值:

// Set the test data. 
$test_data = <<<EOT 
06/10/2014 


06/11/2014 
EOT; 

// Check for any extra returns or white spaces. 
$date_array = preg_split("/(\r\n|\r|\n)/", $test_data, -1); 

// Use 'array_filer' and 'array_values' to shake out the date array. 
$date_array = array_values(array_filter($date_array)); 

// Check the cleaned date array by dumping the data. 
echo '<pre>'; 
print_r($date_array); 
echo '</pre>'; 

輸出將是:

Array 
(
    [0] => 06/10/2014 
    [1] => 06/11/2014 
) 

或者有關攻擊的空行發出另一種方式如何:也許你應該只使用preg_match_all來匹配您想要的實際日期,而不是與preg_split分開?

// Set the test data. 
$test_data = <<<EOT 
06/10/2014 


06/11/2014 
EOT; 

// Match all of the dates that match your format. 
preg_match_all('/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/is', $test_data, $matches); 

// Set the date array based on the dates matched. 
$date_array = array_values(array_filter($matches[0])); 

// Check the cleaned date array by dumping the data. 
echo '<pre>'; 
print_r($date_array); 
echo '</pre>'; 

的,這個輸出將是:

Array 
(
    [0] => 06/10/2014 
    [1] => 06/11/2014 
) 
+0

但我已經嘗試過array_filter。請注意我在原始帖子中所說的:)它仍然產生上面的空數組...讓我不知道什麼是實際返回,如果它不是null或「」。 – jflay

+0

@jflay適合我。也許你的正則表達式應該是'/(\ r \ n | \ r | \ n | \ n \ n)/'? – JakeGould

+0

@jflay檢查我更新的答案。也許你應該使用'preg_match_all'而不是拆分? – JakeGould

1

優先工作在交替|的格局可能會留下流浪的方式\n或不被視爲空\r。嘗試:

$date_array = preg_split("/\s+/", $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY); 

在這種情況下,PREG_SPLIT_NO_EMPTY可能不是必需的,但我把它放在了安全的地方。

+0

非常有幫助,但我發現它是高級自定義字段中的Wordpress格式問題,將新行轉換爲
標記。我選擇了沒有選擇格式,所有的問題都消失了。謝啦! – jflay