从 html 文本文件 [PHP] 生成字符串

Generate string from html text file [PHP]

试图在 "source.txt"

中更改此字符串
<i data-duration="9.09">Text 1</i>
<i data-duration="11.08">Text 2</i>
<i data-duration="15.02">Text 3</i>

为此:

00:00:00-->00:09:09
Text 1
00:09:09-->00:11:08
Text 2
00:11:08-->00:15:02
Text 3
<?php
if(isset($_POST['ok'])) {
  $path = "source.txt";  
  $newstring = $_POST['teks'];

  // Open source file
  $source = fopen($path, 'w');
  // replace with new html string 
  $new = str_replace($source,$newstring,$source);
  fwrite($source,$new,strlen($newstring));
  fclose($source);

  $new = implode('<br />',file($path));

  $search = '<i data-duration="';
  // Split string with html tag $search
  $firstExplode = explode($search, $new);
  foreach ($firstExplode as $key) {
    $secondExplode = explode('">', $key);
    var_dump($secondExplode);
  }

  //Stuck

}
?>

请帮助我编写正确的程序,我一直在分解字符串。 CMIWW,我不明白 foreach 和访问数组的概念。

我会在客户端呈现字符串并在那里进行转换。像这样

function pad(num) {
  return String("0" + num).slice(-2);
}

function fmtDur(str) {
  var parts = str.split(".");
  var str = "00:";
  if (parts.length == 1) return str + "00:" + pad(parts[0]);
  return str + pad(parts[0]) + ":" + pad(parts[1]);
}
var durs = ["00:00:00"],
  div = document.getElementById("durDiv");

document.querySelectorAll("[data-duration]").forEach(function(elem) {
  durs[durs.length] = fmtDur(elem.getAttribute("data-duration"));
  newNode = elem.cloneNode();
  newNode.innerHTML = durs[durs.length - 2] + "-->" + durs[durs.length - 1] + "<br/>" + elem.textContent + "<br/>";
  div.replaceChild(newNode, elem);
});
<div id="durDiv">
  <i data-duration="8">Text 1</i>
  <i data-duration="9.09">Text 2</i>
  <i data-duration="11.08">Text 3</i>
  <i data-duration="15.02">Text 4</i>
</div>

如果你真的想在服务器端格式化这个字符串,你可以使用正则表达式 (RegEx) 和一些 string manipulation 函数:

function format_duration($input) {
    $duration = 0.0;
    $text = '';
    preg_match_all('/"([0-9.]+)">(.*)</', $str, $match); // Save the durations in an array

    for ($i=0; $i < count($match[1]); $i++) {
        // Format start duration
        $start = implode(':', str_split(str_pad(str_replace('.', '', $duration), 6, "0", STR_PAD_LEFT), 2));
        // Format end duration
        $end = implode(':', str_split(str_pad(str_replace('.', '', $match[1][$i]), 6, "0", STR_PAD_LEFT), 2));

        $text .= $start . '-->' . $end . "\r\n";
        $text .= $match[2][$i] . "\r\n";

        // Set the start duration for the next one
        $duration = $match[1][$i];
    }

    return $text;
}

// As the function needs a string, you can use file_get_contents()
echo format_duration(file_get_contents('source.txt'));

格式说明: