我正在尝试搜索我的orderid,这是我到目前为止的代码:
<?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$
现在当我搜索177时,我得到这样的结果: -
Found matches:
176|RC456456456|54156456465|177$
177|RC456456456|54156456465|129$
但我想在177搜索我的第一个字符串
我想要这样的结果,它只匹配我的第一个字符串而不是所有4个变量
177|RC456456456|54156456465|129$
答案 0 :(得分:2)
您希望仅匹配以 177
开头的字符串 。如果是,您可以将正则表达式更改为:
$pattern = "/^$pattern.*$/m";
答案 1 :(得分:0)
$pattern = "/^$pattern/m"; // your string starts (^) with $pattern (177)
// and we dont care what it ends with
答案 2 :(得分:0)
http://sandbox.phpcode.eu/g/3fff8.php
$pattern = "/^$pattern.*?\$/m";
而不是
$pattern = "/^.*|$pattern.*\$/m";