在PHP中搜索文本文件

时间:2017-07-17 22:30:17

标签: php preg-match preg-replace-callback

尝试在文本文件中搜索字符串,并将其替换为HTML代码,该代码是外部文件引用 OR 同一文件中的锚点/书签。

添加了图表。

蓝线:如果存在具有相应名称的文件,则替换为该文件的HREF链接。

红线:如果文件不存在 AND ,则可以在本地文件中找到引用,然后它是指向锚点/书签的HREF链接。

感谢ArminŠupuk先前的回答,这帮助我完成了蓝线(这是一种享受!)。然而,我正在努力理清红线。即在本地文件中搜索相应的链接。

Amended Diagram

最后,这是我一直走下去的路,但未能在Else If获得一场比赛;

$file = $_GET['file'];
$file1 = "lab_" . strtolower($file)  . ".txt";
$orig = file_get_contents($file1);
$text = htmlentities($orig);
$pattern2 = '/LAB_(?<file>[0-9A-F]{4}):/';
$formattedText1 = preg_replace_callback($pattern, 'callback' , 
$formattedText);

function callback ($matches) {

if (file_exists(strtolower($matches[0]) . ".txt")) {
return '<a href="/display.php?file=' . strtolower($matches[1]) . '" 
style="text-decoration: none">' .$matches[0] . '</a>'; }

else if (preg_match($pattern2, $file, $matches))

{

return '<a href = "#LAB_' . $matches[1] . '">' . $matches[0] . '</a>'; }

else {
return 'LAB_' . $matches[1]; }
}

Current output diagram

1 个答案:

答案 0 :(得分:0)

有些事情:

  1. 尝试以一些通常的格式编写代码。请遵循一些代码样式指南,至少是您自己的。使其连贯。
  2. 不要使用名称为$formattedText1$pattern2的变量。说出不同之处。
  3. 使用anonymous functions (Closures)而不是为只使用一次的函数编写函数声明。
  4. 我重命名了一些变量,以便更清楚地了解发生了什么并删除了不必要的内容:

    $fileId = $_GET['file'];
    $fileContent = htmlentities(file_get_contents("lab_" . strtolower($fileId)  . ".txt"));
    
    //add first the anchors
    $formattedContent = preg_replace_callback('/LAB_(?<file>[0-9A-F]{4}):/', function ($matches) {
      return '<a href="#'.$matches[1].'">'.$matches[0].':</a>';
    }, $fileContent);
    //then replace the links
    $formattedContent = preg_replace_callback('/LAB_(?<file>[0-9A-F]{4})/', function ($matches) {
      if (file_exists(strtolower($matches[0]) . ".txt")) {
        return '<a href="/display.php?file=' . strtolower($matches[1]) .
          '"style="text-decoration: none">' .$matches[0] . '</a>';
      } else if (preg_match('/LAB_' . $matches[1] . ':/', $formattedContent)) {
        return '<a href = "#LAB_' . $matches[1] . '">' . $matches[0] . '</a>';
      }  else {
        return 'LAB_' . $matches[1]; }
    }, $formattedContent);
    
    echo $formattedContent;
    

    应该清楚发生了什么。