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.
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]; }
}
Some things:
$formattedText1
or $pattern2
. Name the difference.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.