使用PHP将HTML转换为ASCII
将ASCII文本转换为HTML的相反过程是将HTML转换为ASCII。为此,这里有一个执行此操作的小功能。
function html2ascii($s) { //转换链接 $s = preg_replace('/]*)"?[^>]*>(.*?)<\/a>/i','$2 ($1)',$s); //转换p,br和hr标签 $s = preg_replace('@<(b|h)r[^>]*>@i',"\n",$s); $s = preg_replace('@]*>@i',"\n\n",$s); $s = preg_replace('@
]*>(.*)@i',"\n".'$1'."\n",$s); //转换粗体和斜体标签 $s = preg_replace('@]*>(.*?)@i','*$1*',$s); $s = preg_replace('@]*>(.*?)@i','*$1*',$s); $s = preg_replace('@]*>(.*?)@i','_$1_',$s); $s = preg_replace('@]*>(.*?)@i','_$1_',$s); //解码任何实体 $s = strtr($s,array_flip(get_html_translation_table(HTML_ENTITIES))); //解码编号的实体 $s = preg_replace('/(\d+);/e','chr(str_replace(";", "", str_replace("","","$0")))', $s); //剥离所有剩余的HTML标签 $s = strip_tags($s); //返回字符串 return $s; }要使用此功能,只需将其传递一个字符串即可。这是一个正在工作的例子。
$htmlString = 'This is some XHTML markup that will be
'; echo html2ascii($htmlString);
turned into an ascii string.产生以下输出。
This is some *XHTML* markup that _will_ be turned into (http://www.hashbangcode.com/) an ascii string