2017-08-24 41 views
0

newbee ...如何使用使preg_split(),而不是分裂()這裏

我想更換分流()在一個網站的功能,所以我發現使preg_split()使用。首先要找出分裂()函數是如何工作的,所以我看了看這個例子在php.net網站:

<?php 
// Delimiters may be slash, dot, or hyphen 
$date = "04-30/1973"; 
list($month, $day, $year) = split('[/.-]', $date); 
echo "Month: $month; Day: $day; Year: $year<br />\n"; 
?> 

的產量預期: 月:04;第30天;年份:1973

所以我認爲這將是容易的,只是將其更改爲:

<?php 
// Delimiters may be slash, dot, or hyphen 
$date = "04-30/1973"; 
list($month, $day, $year) = preg_split('[/.-]', $date); 
echo "Month: $month; Day: $day; Year: $year<br />\n"; 
?> 

輸出: 月:04-30/1973;天: ;年份:

我的想法出了什麼問題?

回答

2

只需添加一些符號來定義正則表達式的開始/結束。它可以是~,例如:

$date = "04-30/1973"; 
list($month, $day, $year) = preg_split('~[/.-]~', $date); 
echo "Month: $month; Day: $day; Year: $year<br />\n"; 

更新

如果你的代碼與/爲正則表達式的邊界,那麼你必須逃離/用反斜槓:

list($month, $day, $year) = preg_split('/[\/.-]/', $date); 
+0

改變但輸出仍然相同:輸出:月份:04-30/1973;天: ; Year: – Maurice69

+0

Nope,https://3v4l.org/03TLO –

+0

好吧,我得到了一點,它必須是/而不是如果一個〜像**列表($ month,$ day,$ year)= preg_split(' /[.-]/',$ date); **但是現在仍然需要找到如何將/作爲分割字符。 – Maurice69