从文件获取值-php
假设我的文本文件中有:从文件获取值-php,php,strpos,Php,Strpos,假设我的文本文件中有: Author:MJMZ Author URL:http://abc.co Version: 1.0 如果我查找字符串“Author”,如何获取字符串“MJMZ” 我已经尝试了另一个问题()的解决方案,但没有成功 问题可能是由于strpos功能造成的。在我的例子中,“作者”这个词有两个。因此strps函数无法解决我的问题。请尝试以下操作: $file_contents = file_get_contents('myfilename.ext'); preg_match('/
Author:MJMZ
Author URL:http://abc.co
Version: 1.0
如果我查找字符串“Author”,如何获取字符串“MJMZ”
我已经尝试了另一个问题()的解决方案,但没有成功
问题可能是由于strpos
功能造成的。在我的例子中,“作者”这个词有两个。因此strps函数无法解决我的问题。请尝试以下操作:
$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^\r\n]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';
echo $code;
现在$matches变量应该包含MJMZ
上面,将在文件中搜索作者:code_HERE
的第一个实例,并将code_HERE
放置在$matches
变量中
更具体地说,是正则表达式。将搜索以单词
Author
开头的字符串,后跟可选空格\s*
,后跟分号字符\:
,后跟可选空格\s*
,后跟一个或多个非新行的字符[^\r\n]+
使用分解法在:
处拆分每一行,然后检查前缀是否与您要搜索的内容匹配:
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
list($prefix, $data) = explode(':', $line);
if (trim($prefix) == "Author") {
echo $data;
break;
}
}
若您的文件将包含以数字方式添加的项,那个么您可以将其排序到数组中
$content = file_get_contents("myfile.txt");
$line = explode("\n", $content);
$item = new Array();
foreach($line as $l){
$var = explode(":", $l);
$value = "";
for($i=1; $i<sizeof($var); $i++){
$value .= $var[$i];
}
$item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];
$content=file\u get\u contents(“myfile.txt”);
$line=explode(“\n”,$content);
$item=新数组();
foreach($l行){
$var=explode(“:”,$l);
$value=“”;
对于($i=1;$i首先从文件中获取行,转换为数组,然后按键调用它们
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
}
} else {
// error opening the file.
}
fclose($handle);
echo $array['Author'];
与其搜索作者
不如搜索作者:
?