尝试在文本文件中搜索字符串,并将其替换为HTML代码,该代码是外部文件引用 OR 同一文件中的锚点/书签。
添加了图表。
蓝线:如果存在具有相应名称的文件,则替换为该文件的HREF链接。
红线:如果文件不存在 AND ,则可以在本地文件中找到引用,然后它是指向锚点/书签的HREF链接。
感谢ArminŠupuk先前的回答,这帮助我完成了蓝线(这是一种享受!)。然而,我正在努力理清红线。即在本地文件中搜索相应的链接。
最后,这是我一直走下去的路,但未能在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]; }
}
答案 0 :(得分:0)
有些事情:
$formattedText1
或$pattern2
的变量。说出不同之处。我重命名了一些变量,以便更清楚地了解发生了什么并删除了不必要的内容:
$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;
应该清楚发生了什么。