0

I need a help with replacing a word from a text file to a link using php

This is my code:

<?php
$search = 'google';
$lines = file('f.txt');
foreach($lines as $line)
{
   if(strpos($line, $search) !== false)
   echo $search."\n";
   echo preg_replace('/google/', '<a href="http://www.google.com/'></a>',$lines);

   }
}
?>
M.Fooz
  • 11
  • 1
    check http://stackoverflow.com/questions/11901521/replace-string-in-text-file-using-php and http://stackoverflow.com/questions/20039823/find-and-replace-word-in-text-file – Saty Jun 17 '16 at 09:11
  • 1
    You have a typing mistake here ' – K.I Jun 17 '16 at 09:47
  • Your link still needs to have the original text between the `...`` tags, otherwise there won't be anything to click. – Simba Jun 17 '16 at 10:52

1 Answers1

0

I have a little example coded up for you that will illustrate the general idea.

<a href="<?= $_SERVER['PHP_SELF']; ?>?replace=yes">Replace a word</a>

The $_SERVER['PHP_SELF'] variable points to the current file.

if (isset($_GET['replace']) && $_GET['replace'] == 'yes') {

    // Define filename
    $filename = 'somefile.txt';

    // Get file contents
    $contents = file_get_contents($filename);

    // Replace the word
    $contents = str_replace('someword', 'replacewith', $contents);

    // Write back to file
    file_put_contents($filename, $contents);
}
Peter
  • 8,776
  • 6
  • 62
  • 95