2011-05-16 140 views
1

我有兩個字符串是從文件中拉出來的。我試圖先通過做一個str_replace去掉他們的標籤(如),並用一個空格替換它們。不幸的是,這似乎不起作用,因爲當我在窗體中回顯結果時,我仍然看到標籤。str_replace工作不正常PHP

任何想法?

# 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\">"; 
+0

你試過strip_tags嗎? – locrizak 2011-05-16 17:47:00

+1

第一天寫PHP,讓我有些鬆懈。 – n0pe 2011-05-16 18:02:28

回答

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

或者使用

用strip_tags

+0

我喜歡strip_tags很多,謝謝! – n0pe 2011-05-16 17:58:25

4

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

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

$desc_new相同。閱讀文檔以獲取更多細節。

+0

該死的,這是第二次 - _-謝謝:)我太累了。 – n0pe 2011-05-16 17:47:19

+0

不用擔心。根據評論,我同意'strip_tags()'在這種情況下可能是更好的功能。 – 2011-05-16 17:48:52

1

剝去標籤的最佳方式,使用PHP的時候,是HTMLPurifier

我不會嘗試做類似的東西與str_replace函數。很可能是你犯了一個錯誤。

2

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

至於其他的答案已經提到你需要分配返回值如$title_new = str_replace("<title>"," ", $title_new);,但我極力鼓勵你se strip_tags()爲其預期的目的。

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

此外,它可能無需逐行解析文件。使用file_get_contents()之類的文件立即讀取整個文件的速度要快很多倍,然後使用正則表達式或xml解析器。