2011-08-18 99 views
1

我想搜索我的訂單ID,這是到目前爲止我的代碼:搜索從dat文件

<?php 
$file = 'order.dat'; 
$searchfor = '177'; 

// the following line prevents the browser from parsing this as HTML. 
header('Content-Type: text/plain'); 

// get the file contents, assuming the file to be readable (and exist) 
$contents = file_get_contents($file); 
// escape special characters in the query 
$pattern = preg_quote($searchfor, '/'); 
// finalise the regular expression, matching the whole line 
$pattern = "/^.*$pattern.*\$/m"; 
// search, and store all matching occurences in $matches 
if(preg_match_all($pattern, $contents, $matches)){ 
    echo "Found matches:\n"; 
    echo implode("\n", $matches[0]); 
} 
else{ 
    echo "No matches found"; 
} 

現在比如我order.dat文件中包含的數據

175|RC456456456|54156456465|109$ 

176|RC456456456|54156456465|177$ 

177|RC456456456|54156456465|129$ 

178|RC456456456|54156456465|129$ 

現在時我searchfor 177我有這樣的結果: -

Found matches: 
176|RC456456456|54156456465|177$ 
177|RC456456456|54156456465|129$ 

但我想搜索177我的第一個字符串onl Ÿ

我想我的結果是這樣,它唯一的不匹配上的所有4個變量

177|RC456456456|54156456465|129$ 

回答

2

看起來要匹配只有那些字符串177開始我的第一個字符串。如果是的話,你可以你的正則表達式更改爲:

$pattern = "/^$pattern.*$/m"; 
+0

:)我希望我的結果是這樣的,177 | RC456456456 | 54156456465 | 129 $ – John

+0

@David:更新了答案。 – codaddict

+0

:)謝謝你很多...可以üPLZ給我提供任何研究的鏈接 – John

0
$pattern = "/^$pattern/m"; // your string starts (^) with $pattern (177) 
          // and we dont care what it ends with 
0

http://sandbox.phpcode.eu/g/3fff8.php

$pattern = "/^$pattern.*?\$/m"; 

,而不是

$pattern = "/^.*|$pattern.*\$/m"; 
+0

:)我想要這個結果177 | RC456456456 | 54156456465 | 129 $ – John

+0

sry,錯誤的地址 – genesis

+0

:)如果我想從日期搜索它,我可以做什麼,你可以幫我嗎? – John