2017-07-17 142 views
-2

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

已添加图表。

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

红线:如果文件不存在AND该引用可以在本地文件中找到,那么它是一个HREF链接到锚/书签。

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

Amended Diagram

最后,这是我一直在标题下的路径,其未能在否则如果获得匹配;

$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

前几天你没有问过完全一样的东西吗?有些麻烦? –

+1

为什么你不使用数据库呢? –

+0

@Armin - 类似但略有不同! – TimJ

回答

0

有些事情:

  1. 尝试写下你的代码中一些常用的格式。遵循一些代码造型指南,至少你自己。使其连贯一致。
  2. 请勿使用名称为$formattedText1$pattern2的变量。命名差异。
  3. 使用anonymous functions (Closures)而不是编写函数声明的函数,你只能使用一次。

我改名一些变量,以使其更清晰这是怎么回事,并去除不必要的东西:

$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; 

应该清楚发生了什么事情。

+0

非常感谢。现在理解这个代码会更好一些 - 但是最终的结果还是很困难。稍微修改了一下这个图表,试图更好地解释它。外部文件链接的工作方式与标记本地文件中的书签一样 - 但我仍然遇到问题,试图将每个文件中的链接添加到同一文件中的书签中。 – TimJ

+0

如果你可以用当前结果的一部分编辑你的问题,然后用那个例子解释什么是不正确的,这将会有所帮助。我很抱歉,但你有一个复杂的格式问题,并修复它没有应格式化的文件是该死的难。 –

+0

添加新图来尝试显示当前脚本输出。脚本做3件事。 步骤(1)在LAB_xxxx格式的文件中搜索所有内容:并将其变为书签。这工作。 步骤(2)是在Web服务器上查找与LAB_xxxx格式相同名称的文件名的任何匹配项,如果找到,则创建一个到该文件的HTML链接。这也适用。 步骤(3)是查找LAB_xxxx格式中未被步骤(2)拾取的任何剩余文本,并将其转变为超链接到步骤(1)中创建的书签。这是我正在努力的一点。 – TimJ