[英]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);
使用PHP時,剝離標簽的最佳方法是HTMLPurifier
我不會嘗試使用str_replace做類似的事情。 很可能會犯錯。
$title_new = str_replace(array("<title>", "</title>")," ", $file_lines[$title_line]);
$desc_new = str_replace(array("<description>","</description>")," ", $file_lines[$desc_line]);
或使用
strip_tags
正如其他答案提到的那樣,您需要分配返回值,例如$title_new = str_replace("<title>"," ", $title_new);
,但我強烈建議您將strip_tags()
用於預期的用途。
$buffer = strip_tags($buffer, '<title><description>')
另外,可能也沒有必要逐行解析文件。 使用諸如file_get_contents()
類的內容一次讀取整個文件,然后使用正則表達式或xml解析器,將比以前快很多倍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.