【问题标题】:php str_replace returns empty stringphp str_replace 返回空字符串
【发布时间】:2014-03-12 03:55:52
【问题描述】:
<?php

$html = '<form id="form1" name="f1" action="/jk" dummy';

$html = str_replace(
    '<form id="form1" name="f1"',
    '<form id="form1" name="f1" xxxxxxxxxxxxx',
    $html);

echo $html;

为什么结果为空?

我正在使用 PHP 5.3.27 (cli)

谢谢。

【问题讨论】:

  • Runs fine。您确定 HTML 中没有任何特殊字符(例如换行符)吗?此外,如果这来自网页,则应考虑 DOM 或解析方法。
  • 在这里工作正常。您是在浏览器中查看此内容吗?尝试“查看源代码”,以防浏览器隐藏标签。
  • @MarcB 我发誓这可能就是 OP 正在经历的,好电话。
  • 谢谢大家,这正是问题所在,我正在使用 Chrome 浏览器进行测试。

标签: php str-replace


【解决方案1】:
$html = '<form id="form1" name="f1" action="/jk" dummy';
$html = str_replace(
    '<form id="form1" name="f1"',
    '<form id="form1" name="f1" xxxxxxxxxxxxx',
    $html);

echo highlight_string($html, true);

另一种显示方式是:

header("Content-Type: text/plain");
echo $html;

【讨论】:

    【解决方案2】:

    试试这个方法,

    <?php
    echo 'hello<br>';
    $html = "abcde<br>";
    echo $html;
    $a = substr_replace($html,
        'xyzhi',
        0);
    
    echo $a;
    ?>
    

    Str_replace 将需要您要从字符串中替换的单词。我希望这可能有效。

    【讨论】:

      【解决方案3】:

      你可以看看源码 ctr+u你会发现那里替换成功了,但是为什么在浏览器上看不到页?因为浏览器认为它是一个标签。 所以要在浏览器页面上显示它,我们可以使用 htmlentities():

      $html = '<form id="form1" name="f1" action="/jk" dummy';
      $html = str_replace(
          '<form id="form1" name="f1"',
          '<form id="form1" name="f1" xxxxxxxxxxxxx',
          $html);
      
      echo htmlentities($html);
      

      输出

      <form id="form1" name="f1" xxxxxxxxxxxxx action="/jk" dummy
      

      【讨论】:

        猜你喜欢
        • 2021-10-20
        • 2012-05-07
        • 1970-01-01
        • 1970-01-01
        • 2012-07-23
        • 2017-07-03
        • 2015-01-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多