我有一堆文件。我只需要打印文件的 ITEM_DESCRIPTION: 部分。假设每个文件的内容如下所示
// ITEM_DESCRIPTION: Phone 1
// - Android 9.0 (Pie)
// - 64/128 GB
// - Li-Po 3500 mAh
我希望代码显示如下
Phone 1
- Android 9.0 (Pie)
- 64/128 GB
- Li-Po 3500 mAh
到目前为止,我能生产的是
// Phone 1 // - Android 9.0 (Pie) // - 64/128 GB // - Li-Po 3500 mAh
我想如何用新行分隔双斜杠?
这是我的代码
// Get file path
// This code inside for loop which i don't write here
$filedir=$filelist[$i];
//Display Item Description
$search = "ITEM_DESCRIPTION";
$endsearch = "BRAND";
$contents = stristr(file_get_contents($filedir), $search);
$description = substr($contents, 0, stripos($contents, $endsearch));
$rmv_char = str_replace(str_split('\:'), ' ', $description);
$newline = str_replace(str_split('\//'), PHP_EOL , $rmv_char);
$phone_dscrpn = substr($newline, strlen($search));
这是我尝试过的方法,但行不通
$newline = str_replace(str_split('\//'), PHP_EOL , $rmv_char);
$newline = str_replace(str_split('\//'), "\r\n" , $rmv_char);
最佳答案
看起来原始数据中已经有换行符,因此不需要再次添加它们。您只需要清除斜杠和空格(或制表符,如果它们是什么,很难区分)。
请记住,如果您在浏览器中测试输出,它将不会显示没有 <pre></pre>
的换行符。 .
// Get file path
// This code inside for loop which i don't write here
$filedir=$filelist[$i];
//Display Item Description
$search = "ITEM_DESCRIPTION";
$endsearch = "BRAND";
$contents = stristr(file_get_contents($filedir), $search);
$description = substr($contents, 0, stripos($contents, $endsearch));
//Clear out the slashes
$phone_dscrpn = str_replace("//", "", $description);
//Clear out the spaces
while(strpos($phone_dscrpn," ")!==false) {
$phone_dscrpn = str_replace(" ", " ", $phone_dscrpn);
}
请注意,这将替换描述中的任何双斜杠或双空格。如果这可能是一个问题,那么您将需要考虑更高级的方法(例如逐行)。
关于php - str_用新行替换特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57174202/