str_replace PHP 运行不佳


str_replace Not Working Well PHP

我有两个字符串是从文件中提取的行。我试图首先通过执行str_replace并用空格替换它们来剥离它们的标签(例如)。不幸的是,这似乎不起作用,因为当我以表单回显结果时,我仍然会看到标签。

有什么想法吗?

# Trim the title and description of their tags. Keep only text.
$title_new = $file_lines[$title_line];
str_replace("<title>"," ", $title_new);
str_replace("</title>"," ", $title_new);
$desc_new = $file_lines[$desc_line];
str_replace("<description>"," ", $desc_new);
str_replace("</description>"," ", $desc_new);
# Echo out the HTML form
echo "<form action='"rewrite.php'" method='"post'">";
echo "Title: <input type='"text'" name='"new_title'" size='"84'" value='"".$title_new."'">";
echo "</input>";
echo "<br>Article Body:<br>";
echo "<textarea rows='"20'" cols='"100'" wrap='"hard'" name='"new_desc'">".$desc_new."</textarea><br>";
echo "<input type='"hidden'" name='"title_line'" value='"".$title_line."'">";
echo "<input type='"hidden'" name='"title_old'" value='"".$file_lines[$title_line]."'">";
echo "<input type='"hidden'" name='"desc_line'" value='"".$desc_line."'">";
echo "<input type='"hidden'" name='"desc_old'" value='"".$file_lines[$desc_line]."'">";
echo "<input type='"submit'" value='"Modify'" name='"new_submit'">";

str_replace() 返回修改后的字符串。所以你需要分配它:

$title_new = str_replace("<title>"," ", $title_new);

$desc_new相同。阅读文档了解更多详情。

str_replace返回字符串,所以你应该这样做:

$title_new = str_replace("<title>"," ", $title_new);
$title_new = str_replace("</title>"," ", $title_new);
$desc_new = str_replace("<description>"," ", $desc_new);
$desc_new = str_replace("</description>"," ", $desc_new);
 $title_new = str_replace(array("<title>", "</title>")," ", $file_lines[$title_line]);
 $desc_new = str_replace(array("<description>","</description>")," ", $file_lines[$desc_line]);

或使用

strip_tags

使用 PHP 时,去除标签的最佳方法是 HTMLPurifier

我不会尝试对str_replace做这样的事情。很可能一个人会犯错误。

正如其他答案所提到的,您需要像$title_new = str_replace("<title>"," ", $title_new);一样分配返回值,但我强烈建议您将strip_tags()用于其预期目的。

$buffer = strip_tags($buffer, '<title><description>')

此外,可能没有必要逐行解析文件。使用类似 file_get_contents() 的内容一次读取整个文件,然后使用正则表达式或 xml 解析器会快很多倍。