2017-04-11 128 views
1

我最近開始使用PHP,並試圖從.txt創建一個列表,但刪除所有不必要的組件。 線得到這個是否可以結合strtok()和substr()?

item = 0 egg came_from_chicken 

我想刪除item =並給我留下0 eggcame_from_chicken。 現在經過一番搜索,我發現substr()刪除我的每一行的前5個字符。後來我也發現strtok()可以在第二個標籤後刪除剩餘的不需要的文本。不幸的是我不能合併這些。所以我的問題是:如何從每行刪除前5個字符,並刪除每行之後的第二個選項卡後的所有內容?

我有了這個迄今:

<?php 
$lines = file('../doc/itemlist.txt'); 
$newf = array(); 
foreach ($lines as $line) { 
    $newf[] = strtok($line, "\t") . "\t" . strtok("\t"); 
} 
var_dump($newf); 
?> 

這就像一個魅力egg後刪除一切,但還是要刪除item =

+0

因爲「item =」沒有被製表符分開。你能在文件中顯示一個字符串的抽象格式嗎? – user4035

+0

不太清楚你的意思是抽象的格式,但我希望這是你在找什麼:https://gyazo.com/da5b84be7bdc5b4bc6e7fd32a3815ce6對不起,我真的磨砂仍然是:P – TheRealDeal

回答

0

快速和骯髒的方法是隻包了一切:

$newf[] = substr(strtok($line, "\t") . "\t" . strtok("\t"), 5); 

但是,我個人有strtok()不順眼(不能解釋爲什麼,我只是不喜歡它)。如果你不需要從第二個選項卡,但從最後選項卡(在你的例子中第二個選項卡是最後一個選項卡),我會使用strrpos()找到最後一個選項卡的位置,並轉儲到substr()

$newf[] = substr($line, 5, strrpos($line, "\t")-5); 

-5是爲了補償5個字符,你從一開始就脫掉。如果您需要從字符6開始而不是5,那麼您應該從任何strrpos()退貨中減去6。

編輯別介意整個最後一部分,我剛纔看到您發佈的示例格式,你真的需要第二個選項卡,而不是最後一個標籤。

+0

真正你的快速和骯髒的方式工作得很好!我的例子確實只有2個標籤,但真正的格式包含更多。謝謝你的回答,非常感謝 – TheRealDeal

0

該方法將與任何字符串一起使用,該字符串位於=符號之前。

foreach ($lines as $line) { 
    $newf[] = implode("\t", array_slice(explode("\t", trim(explode('=', $line, 2)[1])), 0, 2)); 
} 
+0

哦,工作!謝啦。完全沒有停下來考慮內爆和爆炸... – TheRealDeal

0

您可以使用正則表達式:

<?php 
$lines = file('./file.txt'); 
$newf = array(); 
foreach ($lines as $line) { 
    $newf[] = preg_replace('/.*=\s*(.*)\t.*/s', '$1', $line); 
} 

var_dump($newf); 

輸出:

array(1) { 
    [0]=> 
    string(5) "0 egg" 
} 
0

假設您將收到類似的模式,以你給的例子。

你可以做一個簡單的一行:

$str = "item = 0 egg came_from_chicken"; 
$parts = preg_split('/\s+/', $str); 
echo $parts[2] . $parts[3]; 
0

我知道這是不是你正在尋找使用strtok的答案,但我相信這將是很容易做下面的下面的代碼:

<?php 
    $lines = '../doc/itemlist.txt'; 

    // array to store all data 
    $newf = array(); 

    foreach ($lines as $line) { 
     // you can do an explode which will turn it into an array and you can then get any values you want 
     // $newf [] = strtok ($line, "\t") . "\t" . strtok("\t"); // throw away 

     // lets say we use [item = 0 egg came_from_chicken] as our string 
     // we split it into an array for every tab or spaces found 
     $values  = preg_split ('/\s+/', $line); 
     //returns 
     // Array 
     // (
     //  [0] => item 
     //  [1] => = 
     //  [2] => 0 
     //  [3] => egg 
     //  [4] => came_from_chicken 
     //  [5] => 
     // ) 

     // lastly store your values which would be sub 2 and sub 4 
     $newf [] = $values [2] . ' ' . $values [3]; 
    } 

    var_dump($newf); 

    // return 
    // array (size=3) 
    // 0 => string '0 aaa' (length=5) 
    // 1 => string '1 bbb' (length=5) 
    // 2 => string '2 ccc' (length=5) 
?> 
相關問題