我做一个file_get_contents
来获得一个长文件,我想找到以"MyParam"开始的行(只有一个)(例如)。我不想一行一行地切割文件,我只想用preg_match
(或等效的)来做。我尝试了很多事情,但没有成功。提前感谢
//some text
//some text
//MyParam "red"
//some text
MyParam "blue"
Some text
// Some text
我只想得到MyParam "blue"
。
如果您必须使用正则表达式,您可以这样做:
preg_match('/^MyParam[^'r'n]*/m', $text, $matches);
var_dump($matches[0]);
解释:
-
[^'r'n]
-匹配除'r
或'n
以外的任何字符的字符类。 -
m
-多行修饰符,将^
的含义从"断言字符串开头的位置"更改为"断言每行开头的位置"。
这里,$matches[0]
将包含完整匹配的字符串(在这种情况下,这是您想要的)。
string(14) "MyParam "blue""
使用file_get_contents在这里不是最好的选择,因为您可以逐行读取文件
$handle = fopen("yourfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (strpos($line, 'MyParam')===0) {
echo 'found';
break;
}
}
} else {
echo 'error opening the file';
}
fclose($handle);
注意:如果你需要在引号之间提取参数值,你可以使用:
$value = explode('"', $line, 3)[1];
不需要regexp:
$pos = strpos($filecontent, "'nMyParam");
$endline = strpos($filecontent, "'n", $pos + 1);
$line = substr($filecontent, $pos + 1, $endline - $pos - 1) ;
未测试,字符串中可能有+-1的偏移量,但它给了你一个想法。
Edit:如果您确定"MyParam"不出现在文件的其他地方,您可以删除第一个"'n"。
可以使用strpos()来查找子字符串在字符串中第一次出现的位置。
http://nl1.php.net/strpos这里我将考虑几种不同的方法。需要考虑的最重要的事情是,您不需要通过file_get_contents()
将整个文件读入内存。我倾向于使用shell命令来完成:
$file = '/path/to/file';
$search_pattern = '^MyParam';
$file_safe = escapeshellarg($file);
$pattern_safe = escapeshellarg($search_pattern);
$result = exec('grep ' . $pattern_safe . ' ' . $file_safe);
或者,您可以一次一行地读取文件,查找匹配项:
$result = '';
$file = '/path/to/file';
$search = 'MyParam'; // note I am not using regex here as this is unnecessary in your case
$handle = fopen($file, 'r');
if ($handle) {
while($line = fgets($handle) !== false) {
if (strpos($line, $search) === 0) { // exact match is important here
$result = $line;
break;
}
}
fclose($handle);
}