我有txt文件,我需要循环回显特定数据。
假设我的txt文件名为:myfile.txt
内部结构如下:
etc="Orange" src="stack1"
etc="Blue" src="stack2"
etc="Green" src="stack3"
etc="Red" src="stack4"
如何在PHP中回显这些值:橙色,蓝色,绿色,红色?
答案 0 :(得分:1)
您可以使用preg_match_all
:
<?php
# get your text
$txt = file_get_contents('your_text_file.txt');
# match against etc="" (gets val inside the quotes)
preg_match_all('/etc="([^"]+)"/', $txt, $matches);
# actual values = $matches[1]
$values = $matches[1];
echo '<pre>'. print_r($values, 1) .'</pre>';
答案 1 :(得分:1)
$content = file_get_content("/path/to/myfile.txt", "r");
if (false === $content) {
// handle error if file can't be open or find
}
preg_match_all('/etc="(.*?)"/', $content, $matches);
echo implode($matches[1], ',');
使用file_get_content
可以检索文件中的内容。
之后,您需要检查file_get_content
是否返回了错误代码(在这种情况下为false
)。
preg_match_all
将使用RegExp筛选出您所需的内容。特别是:
/ #is a delimiter needed
etc=" #will match literally the letters etc="
(.*?) #is a capturing group needed to collect all the values inside the "" part of etc value. So, capturing group is done with (). .* will match every character and ? make the quantifier "non greedy".
/ #is the ending delimiter
所有匹配项都收集在$matches
数组内(不必事先定义$matches
。
最后,您需要将收集的值转换为字符串,并可以使用implode
函数。
答案 2 :(得分:0)
我在代码//comments
上全部检查。
<?php
$fichero = file_get_contents('./myfile.txt', false);
if($fichero === false){ //if file_get_contents() return false, the file isn't found, if its found, return data.
echo "Can't find file.\n";
}else{ //If file is find, this condition is executed.
$output = array(); //this variable is who will get the output of regular expression pattern from next line function.
preg_match_all('/([A-Z])\w+/',$fichero, $output);
for($i = 0; $i < count($output[0]); $i++){ //Iterate throught the first array inside of array of $output, count(array) is for get length of array.
echo $output[0][$i]; //Print values from array $output[0][$i]
if($i + 1 != count($output[0])){ //if not equal to length of array, add , at end of printed value of output[0][$i]
echo ', ';
}else{ //if equal to length of array, add . at end of printed value of $output[0][$i]
echo '.';
}
}
}
?>