2012-12-24 41 views
1

我是編程新手,我試圖構建一個用於個人使用的小型php價格比較腳本。我已經設法解析一個網上商店的網站(使用簡單的dom解析器),並得到一個(某種)清理的字符串,其中有一個層級和一個價格。在2個變量的PHP分割字符串

我與現在格式化喜歡這個工作的字符串:

" 50 27,00 " //50 pieces of a product cost €27,00 (without the ""s) 
"1000 26,60 " //1000 pieces of a product cost €26,60 

我想抓住的字符串$層的第一部分和第二部分(包括逗號)字符串$價錢。

你能幫我怎麼做嗎?有時會發生變化(見上面的例子中的空間,開始串總是有2個白色的空間,中間

陣列將被罰款也是,如果我能得到它,像這樣(內部消除空格):

$pricearray = array(50, "27,00"); //string to number will be my next problem to solve, first things first 

我想我必須使用使preg_split,但現在不表達使用

感謝您對我的思想

+0

http://stackoverflow.com/questions/1063087/how-to-split-a-string-with-php –

+0

唐不會陷入陷阱,認爲你必須對每個涉及字符串的編程問題使用正則表達式。通常有更簡單的方法來實現常見任務,例如在空白處分割字符串。我建議閱讀[所有內置的PHP字符串函數](http://php.net/manual/en/ref.strings.php)並瞭解可用的內容。 –

回答

4

最簡單的方法是調用explode功能:。

$string = '1000 26,60'; 
$pricearray = explode(' ', $string); 

但首先,你必須擺脫所有不必要的空間:

$string = trim($string); // remove spaces at the beginning and at the end 
$string = preg_replace('/\s+/', ' ', $string); // replace 1+ spaces with 1 space 

空間置換法是從this question拍攝。謝謝,codaddict!

+0

謝謝卡夏夫。它工作完美!我無法工作的唯一的事情是preg_replace。它繼續使用2個空格,因此陣列中有一個空間。 – Wiz

+0

如果我的回答滿意你,你可以upvote並接受它:) – akashivskyy

1

那麼,正則表達式引擎是很難理解,但他們可以輕鬆地做這些可選空間。

讓我們看看,如果我沒有犯錯的正則表達式:

$yourarray = array(); 
//just extract the pattern you want 
preg_match('/([0-9]+) + ([0-9]+,[0-9]+)/', " 50 27,00 ", $yourarray); 
var_dump($yourarray); 
preg_match('/([0-9]+) + ([0-9]+,[0-9]+)/', "1000 26,60 ", $yourarray); 
var_dump($yourarray); 

// validate and extract the pattern you want 
if (!preg_match_all('/^ *([0-9]+) +([0-9]+,[0-9]+) *$/', " 50 27,00 ", $yourarray)) 
    print "error"; 
else 
    var_dump($yourarray); 
if (!preg_match_all('/^ *([0-9]+) + ([0-9]+,[0-9]+) *$/', "1000 26,60 ", $yourarray)) 
    print "error"; 
else 
    var_dump($yourarray); 
if (!preg_match_all('/^ *([0-9]+) + ([0-9]+,[0-9]+) *$/', "1000 26 ", $yourarray)) 
    print "error"; 
else 
    var_dump($yourarray);