dougang5088 2019-07-12 12:39
浏览 410
已采纳

PHP在字符串中搜索/替换Word,并仅更改替换字的字体颜色

I have a text box, a search field, and a replace field. I want to perform a search and replace for the text in my text box and change the color of the font for any of the replaced words. I would like any words that are not replaced to remain the font color they were before the search/replace was performed.

Scratching my head on this one though. Here's the code I've got so far:

<body>

  <form id="form1" name="form1" method="post" action="">

    <p><br/>
      <textarea name="textarea" id="textarea" cols="70" rows="10">
        <?php
            if(isset($_POST["submit"])) {
                $search = $_POST["search"];
                $replace = $_POST["replace"];
                $textarea = $_POST["textarea"];

                $newtext = str_replace($search,$replace,$textarea);
                echo $newtext;
            } 
        ?>
    </textarea>
    </p>

    <p>
      <label for="search">Search :</label>
      <input type="text" name="search" id="search" />
    </p>

    <p>
      <label for="replace">Replace</label>
      <input type="text" name="replace" id="replace" />
    </p>

    <p><br/>
      <input type="submit" name="submit" id="submit" value="Submit" />
      <label for="textarea"></label>
    </p>

  </form>

</body>

</div>
  • 写回答

1条回答 默认 最新

  • dousu5608 2019-07-12 12:44
    关注

    You can't change the colour of the text within a textarea.

    You can however echo it out as text:

    <?php
        if(isset($_POST["submit"])) {
            $search = $_POST["search"];
            $replace = '<span style="color: #F00;">' . $_POST["replace"] . '</span>';
            $textarea = $_POST["textarea"];
    
            $newtext = str_replace($search,$replace,$textarea);
            echo $newtext;
        } 
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型