在PHP中搜索文本文件

Trying to search a text file for a string and replace it with HTML code that is either an external file reference OR an anchor/bookmark within the same file.

Have added a diagram.

Blue Lines : If a file with the corresponding name exists, then replace with the HREF link to the file.

Red Lines : If a file doesn't exist AND the reference can be found in the local file, then it's a HREF link to the anchor/bookmark.

Thanks to Armin Šupuk for his previous answer which helped me out doing the Blue Lines (which works a treat!). However, am struggling to sort out the Red Lines. i.e. searching the local file for a corresponding link.

Amended Diagram

Finally, this is the path I've been heading down which fails to get a match at the 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

Some things:

  1. Try to write your code down in some usual format. Follow some code styling guide, at least your own. Make it coherent.
  2. Don't use variables with names like $formattedText1 or $pattern2. Name the difference.
  3. Use anonymous functions (Closures) instead of writing function declaration for functions which you go only to use once.

I renamed some variables to make it clearer what's going on and removed unnecessary stuff:

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

It should be clear what's going on.