2010-08-02 24 views
1

我有一個html文檔,其中包含數百個特殊字符(如em破折號,智能撇號,口音egrave等),我想轉換爲他們的html等價物。如何自動替換所有與HTML等效的特殊字符?

例如,我的文檔中包含 「破折號」( - ),我想轉換爲:

— 

當然,我的HTML文檔中包含HTML標記。我不想將部分html標籤(例如「<」或「>」)轉換爲html等價物。

是否有任何工具(php腳本,網絡應用程序,桌面應用程序等),我可以上傳我的html文檔,並返回相同的文檔,但修改爲包括所需的html等價物?

我有很多文件,有很多特殊字符。我想避免必須使用「查找和替換」(對於每個特殊字符)作爲解決方案...會花費太長時間。

+5

只要正確設置編碼並保留原來的字符呢? – Joey 2010-08-02 18:33:30

+1

Johannes是對的。如果編碼設置正確,則不需要HTML實體。 – Artefacto 2010-08-02 18:44:51

回答

0

如果您仍然想這樣做:

Create a list of special chars with their respective code:

例如:

$htmlNumbers = array("0" => array("char"=>"—", "code"=>"&#8212"), 
         "1" => array("char"=>"@", "code"=>"&#64"), 
         --------------------- 
         --------------------- 
        ); 

現在得到的html文件的HTML內容,並使用str_replace函數的代碼替換所有字符:

$html = file_get_contents("index.html"); 

for($i=0; $i<count($htmlNumbers); $i++) {      
    $html = str_replace($htmlNumbers[$i]['char'] , $htmlNumbers[$i]['code'], $html); 
} 

echo $html; 

現在您可以使用文件處理方法將輸出保存到html文件中。

+0

閱讀OP的問題:「我想避免使用」查找和替換「(對於每個特殊字符)作爲解決方案...將花費太長時間。」 – 2010-08-02 19:10:38

1

你可以使用類似:

<?php 
ob_start(); 
include 'test.html'; 
$content = ob_get_contents(); 
ob_clean(); 
$new = str_replace('<','$start$',$content); 
$new = str_replace('>','$end$',$new); 
$new = htmlentities($new); 
$new = str_replace('$start$','<',$new); 
$new = str_replace('$end$','>',$new); 
echo $new; 
ob_end_flush(); 
?> 

然後就改變的test.html到什麼都檔案要刪除特殊字符

編輯: 這僅僅是自動化的,每一樣的東西在同一目錄下的HTML文件:

<?php 
foreach(glob('*.html') as $file){ 
ob_start(); 
include $file; 
$content = ob_get_contents(); 
ob_clean(); 
$new = str_replace('<','$start$',$content); 
$new = str_replace('>','$end$',$new); 
$new = htmlentities($new); 
$new = str_replace('$start$','<',$new); 
$new = str_replace('$end$','>',$new); 
$file = fopen($file,'w'); 
fwrite($file,$new); 
fclose($file); 
} 
echo 'done'; 
ob_end_flush(); 
?> 
1
$new = str_replace(array('&lt;', '&gt;'), array('<', '>'), htmlentities($old));