【问题标题】:How to replace a word in a file with a hyperlink in PHP?如何用PHP中的超链接替换文件中的单词?
【发布时间】:2016-10-19 01:14:54
【问题描述】:

我需要帮助,将文本文件中的单词替换为使用 php 的链接

这是我的代码:

<?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);

   }
}
?>

【问题讨论】:

标签: php


【解决方案1】:

我为您编写了一个小示例,可以说明总体思路。

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

$_SERVER['PHP_SELF'] 变量指向当前文件。

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);
}

【讨论】:

  • 谢谢。真的很有帮助。
  • @M.Fooz 很高兴能提供帮助。您可以通过接受我的答案作为我答案左侧的最佳答案来感谢我。
猜你喜欢
  • 1970-01-01
  • 2011-03-31
  • 2021-04-02
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
相关资源
最近更新 更多