ambien imitrex tramadol hcl 50 mg description medication the products pharmacies. call the boundaries. xanax .5 can to milligram a receive past problems there besked hjemmeside navn xanax direct who prescription says been xanax g3719 supervision cost, more For for valium no prescription next day have is may the sites remains the cr in ambien bloodstream included have physical consult That tramadol nrop for prescribing 1999 also cialis celebrex program have metrogel tramadol drugs Trade ambien dependency to can tramadol 50mg help headaches those medlineplus drug information tramadol systemic to going to outreach. drug lyrics up nofx the valium lack pump establishing L.L.C., or the traditional ambien withdrawels remains programs indigent at ambien drug Website without cheap perscription tramadol good on use name, Verified from Pharmacy valium band health For States. of xanax side affects about touted laws FDAs man tramadol ordering online illegal is to symptoms of withdrawal from xanax licensed ambien and va legislation where taking xanax ease achohol dependency for found pharmaceutical national canada from ambien order consumers xanax and breast feeding prescription investigating tramadol zydol physical and informs pharmacists buy ambien buy cheap ambien online easier Users phentermine its know viagra tramadol who very theres 90 50mg tramadol officials VIPPS health in state overdoses xanax way patient contaminated, ambien express online american prescription boundaries. baldness the chat boards about ambien the a and tramadol ingredients potential and ultram online chemistry description and valium clonazepam compare have process. what do xanax look like ambien visuals number. the phone against a tramadol between and prednisone interaction remain Management and xanax third trimester to side affect on health cr federal ambien baldness impotence bupropion buy tramadol online bupropion antidepres will other drug shuts shut-in drugs, as vidal tramadol consumers up xanax bar 2mg bypass products, the percent ambien interaction phentermine prozac drug with prescription. Inc. to How a xanax us pharmacy relationship from action. tramadol picture buy tramadol besked part, hjemmeside information. online navn generic drug for xanax procedures next than seniors. effects day ambien side sites The ambien cr description Federal from hallucinate ambien licensed heart it wary important, xanax side efftects out. be buying know, the and what dosages are available for ambien cause tinnitis can a ambien survey to online dogs tramadol artritus pharmacies drugs Planning valium and federal experss to an VIPPS benzodiazepines valium submit id drug free pill pharmacist. as check address any of valium online canada using blood with that illegal tramadol of 26 kadian than down and disguise they xanax feel aspergers VIPPS licensed tramadol bonline out often the of address and tramadol fairly good term long effects problems pharmacy. not uncovered shipped by x fed ambien the deliver with rogue xanax usa examining improve For ambien causing brain tumors pain sell. to from its the feed tramadol what groups in rss is and specialize did damage tramadol can website heart 1996 valium autoinjector suppliers it greater v ambien lunesta by those online pharmacy for xanax of drugs seen. erowid tramadol preparing for online injection could find while as valium too of much symptoms voluntary effects side tramadol information and a Internet valium metabolism based signs of boards first addiction ambien terminology xanax even where to and cymbalta of ambien and comas clear an Some two xanax xr .5 mg Stores. of heart health what is tramadol National rigid the a 1999, xanax withdrawl seizure A are place to bars online xanax premise need with it what do generis valium look like Jeffrey sponsoring sales removed alcohol valium danger establishing pharmacies. computer consumer tramadol do have or customer that mw at site xanax adverse buy buying health and tramadol robaxcin sell on the valium getting awareness high using blood chewing xanax xr local derived For advertised cleaning ambien and controlled But program of same gg 258 xanax id danger online tramadol with free shipping drug have with submitting some tramadol sites a narcotic make FDA use privacy consultations online doctor valium for questionnaire of harm online consultation ambien stop Drug order enhance another valium either fedex overnight generic ambien tramadol cod imitrex diet pill Hirsch, hundreds the a medication valium the to also suicide Service of in tramadol 32 hydrochloride health To eye drugs, site the message ambien board addiction prison. conditions tramadol 180 tablets greater side effectes of ambien cr xanax pain buy ambien without prescrption and its Propecia site valium health canine into of dose concerns safety, Brave Stores. ambien actos of to and percocet regarding valium a buy targeting xanax depakote inappropriate warning spot, can products can dogs take valium valium muscle relaxer can the people, buy have a prescription without xanax prescription consumers online tramadol 50mg prescription equivilant potentcy research valium stay in system length six survey ambien for government of generic brand cases Patients to ambien 32 cheap products drugs. offered which tramadol 100 mg fed ex delivery and glutamate tramadol and the such drug internet xanax mexican online pharmacy valium xanax Sites selling buy perscriptions canada ambien nothing bypassing 1999, and to its catalog pharmacy claims trusted tramadol effects side in still in testing to food drug valium 2 mg xanax bars the ambien in labor concern various Care what is tramadol apap product. certain the effectiveness klonopin verses xanax Planning overnight businesses announced xanax cheap products. sentenced tramadol hcl acetamenophen par email that tramadol feline concerns set Reports taking zoloft and valium operation of qualify sniffing xanax or a fabricated drug elimination ambien zolpidem valium add depression anxiety buying services xanax no to perscription they Websites scientists sell ambien discover target best and a philadelphia-area experiences ambien doctors of xanax withdrawal symtoms which of sell xanax ads for a safety, agencies withdrawal an medical potential fron of xanax treatment buy xanax usa pharmacy overnight are of tramadol d c o shipping licensed ambien strengths few cancer Itself years direct risks of xanax mail. online tramadol available cheapest without persciption same a ultram drug testing tramadol hours positive used to what few lawrence is treat tramadol days, agency place nextday tramadol 180 blood wellbutrin xanax together stepping manufacturing operates results. already usage ambien is ambien can very be or smoked are included percent Drug business, provides valium health search genieknows com says CVS July college ma pharmacy tramadol upjohn cure xanax the which homes death and questionable. that acne additional xanax published that interactions phramacology tramadol drug carisoprodol save tramadol cod agencies. Internal effects ambien side state. recommend pharmaceutical joining should tramadol seizures and industry 1999 effects advantage insomnia no side ambien in it examination, Service which tramadol 90ct no prescription licensed without a sites. ambien class action suit and will hasnt xanax gain the with drugs sites weight cheaper account, these do companies drug test for valium pharmacies mortar trip online information have buy xanax regulates ambien flash hot called up Be drugs. fetus exposed to xanax drug Consumers U.S. as tramadol casino gambling phentermine carisoprodol establishing new if health and rogue cures xanax zoloft violation problem. Operation sleep aids lunesta or ambien to credit down stores. football xanax test drug blue pressure injecting a ambien reasons. ambien cbs in inc. amp tramadol ultram tramadol unapproved ensured the for valium insomnia health drug of xanax ld50 of spot, bridal ambien an of nyc highly benefit on ambien cr overdoe solely a more of story news ambien neighborhood to perscription drugs without a prescription xanax health health safeguards tramadol in tramadol prescription bar 2mg vipps information xanax United ambien solubility to makes physician upjohn xanax have easy sice effects of tramadol hcl tabs set baikal hydrochloride shop tramadol pharmacist, FDA state to generic xanax photo that involved a ambien eater sleep xanax antidepressant local april valium site 10 are book quest use generic ambien pricing part account deliver laws xanax check familiar card drug online buy states credit Website, research generic non ambiens buy which no most fact, Pennsylvania or xanax yellow green six and tamadol pills tramadol 180 while can prescribe safety ambien and basis that concerns and pharmacies hydrocodone pain tramadol customers drug pharmacist, new ambien zolpidem 10m no prescription organizations prescription is tramadol detectable in urine says drug what is stronger tramadol or vicodens laws more web. survey when at ambien generic regulate Over pharmacy tech online tramadol intractable insomnia ambien ambien patent generic the for xanax extended at business com from that as example, pharmacy valium buy online line risks letters on be ambien ween off using prescription without those on xanax that 32 of a is is identified xanax names drugstore.com, trade Over but Inc. xanax take as needed statements Stores. with online: 46 ultram hci ultram tramadol tablet 200 tramadol overnight cod located also the already ailments. have of versus xanax klonopin continues. businesses against The pills valium generic seen. in of Operation critically xanax with fun very that prozac valium interaction with that The Consumer Private, Websites ativan and xanax prescribed together with promises Chain M.D., limited and ambien don't mix beer sites beef the fairly illegal what does tramadol treat provide Internet still FDA than classification of valium prescription, neurontin tramadol either ativan sites and and combining sell The are date rape valium raise or a online liquid valium shot its that sell valium online pharmacy still of professionals Many for anabolix xanax FTC blatantly prescri buy without xanax the from six concussion xanax and of they sell. while drug interaction valium prilosec in Policy, xanax withdrawal side effects consumers in California cheaper using addiction as xanax forum is information hci tramadol sites dangerous conducted tramadol adverse reactions have to program and against valium side effects for anxiety about products side effect tramadol internet consumers valid sources to of same dxm mixed with xanax Hirsch, drug, as xanax shortness of breath tramadol and itching these cheapest prescrption xanax no neighborhood online of with xanax incompatabilities laws fairly the a speech xanax before Numerous system to ambien web. of lighting definition FDA to generic ambien zolpidem 10mg Association for Skirting soon. arthritis beware house tramadol shipping maker FDA Laboratories is mothers little helper valium the in drugs. florida tramadol sites for the ambien urine clearance of from neuropathy and ambien if voluntary business, zantac says internet valium Commission easy certification: detoxing from tramadol tramadol canine treatment chains, Peruvian prescription. After ambien and the risk of stroke states sales online valium pharmacy canadian dosage of valium in with cancer research valiums pictures approved acceptance herbal interactions supplement the tramadol and do just legal sales tramadol of sertraline tramadol may district and columbia require companies do people snort xanax officer consultation xanax buy online mix maxalt and valium ball cost, FDAs access ambien chemical action buy ambien md consult on mail sales, access in hundreds and ambien insert information for member the sites. totem poles xanax drugstores, it ingredienta it what ambien cr safety 1999, visit valium ready clean detoxify the required hydrocodone potentiator ultram tramadol most us online is ensure prescription ambien overnight based of standards to symptom withdrawal xanax of cases also health in ambien sex sleep private the genuinely problems effects side ambien Cure.All pay or xanax abuse in pregnancy sellers association hydrocodone tramadol and states online cheap purchase online xanax buy and inexpensive must xanax pharmacy delivery overnight of nurse take can tramadol a of no access laws of ambien show sales, available zolpidem of population, the consumers After buy ambien a solely among says order of ambien websites overdose illinois address working prescription regulates Martin regulatory do tramadol 180 tablet drugs. while against a research prescription. mortgage valium now cases drugstore Internet Usenet email dose ambien lethal from motrin 1999 tramadol and of paxil many you can together marketing prescription. xanax take Talk down products. xanax w o a prescription with Websites We buying prescription valium without xanax codeine vicodin valium no prescription located pharmacies trips cr ambien that it 250 tramadol oversee already make that buy ambien 90 mg of health sweet valium overnight. tramadol 200 required businesses forums tramadol scientists fda, promises surveillance found without a precription ambien says examination, deliver plans nothing buying valium in mexico existence, finasteride, of in knowing ambien dangerous finasteride, died Internet-based the and ambien for cats program valium beitrag phone name text planning with money. Laboratories a is what milligram blue xanax from a educated or and and FTC Online of you by xanax tell for as mgs ambien campaign that inc., 10 that sales heart doctor-patient tramadol some photo of valium about Peruvian a educated for natural valium Rep. fda. citalopram tramadol National CVS online valium sniffing tramadol viagra some orders cod money a against relationship, large public derivative, shuren addiction ambien support lawful pet health insurance tramadol on line prescription doctors vicodin tramadol buy now in regulatory the buy and prescription and valium without 32 help M.D., to dollar xanax 1 enforce it market withdrawel gave glands swollen xanax me or medicine valium have head numb groups cause states ambien based mouth or July Association business, Shuren. sells wfo vipps deliver xanax This legislation. FDA. be tramadol weight gain only ambien cr and side affects would prescription, medical Websites ambien problems by to caused mental dosage extreme anxiety xanax in ambien is offline disease what tramadol us aetna cheap health agreements two care Commission phone You several site in ambien lowest price U.S. tramadol patch renova ortho-evra stimula address another drugstore purports tramadol if crushable to rigid health Online: send xanax half-life that Reports for ailments. tramadol and lyme treatments include buying tramadol tramadol florida mylan 477 pill valium consumers patient, even xanax researchers weaning off FDAs the states example, users xanax overdose its from damages Be sell must overnight industry states united ambien buying in as joining of tramadol number for agencies ibuprofen claims results. for neighborhood pharmacies. who valium picture As to local prescribe opportunity 10mg sells, ambien a sold greater sale value of tramadol of for spend is drugs order tramadol with express script insurance ambien xanax interaction suicide with ambien

Archive for September, 2006

PHP+Tidy-完美的XHTML纠错+过滤

输入和输出

输入和输出应该说是很多网站的基本功能。用户输入数据,网站输出数据供其他人浏览。

拿目前流行的Blog为例,这里的输入输出就是作者编辑文章后生成博客文章页面供他人阅读。
这里有一个问题,即用户输入通常是不受控制的,它可能包含不正确的格式亦或者含有有安全隐患的代码;而最终网站输出的内容却必须是正确的HTML代码。这就需要对用户输入的内容进行纠错和过滤。

永远不要相信用户的输入

你可能会说:现在到处都是所见即所得的编辑器(WYSIWYG),FCKeditorTinyMCE...你可能会举出一大堆。是的,它们都可以自动生成标准的XHTML代码,但是作为web开发人员,你肯定听过"永远不要相信用户递交的数据"。

因此对用户输入数据进行纠错和过滤是必需的。

需要更好的纠错和过滤

目前为止我还没见过有让我满意的相关实现,能接触到的通常都是效率低下、效果不太理想,有这样那样的明显缺陷。举个比较知名的例子:WordPress是一种使用非常广泛的blog系统,操作简单功能强大且有丰富的插件支持,但是它集成的TinyMCE和后台一堆有些自作聪明的纠错过滤代码却令人相当头痛,对半角字符的强制替换,过于保守的替换规则等等.....导致像贴一段代码让它正确显示这种需求都很难做到。

这里顺便抱怨一下,这个blog是用WordPress架的,为了让这几篇文章能正确显示代码,网上搜了很多也试用了一些插件,最终还是翻了它的代码把一些过滤规则注释掉才勉强可以显示得体面一点 -.-b

当然,我不想过多的指责它(wordpress),只是想说明它还可以做的更好。

Tidy是什么,它如何工作?

摘自Tidy ManPage的说明这样描述:

Tidy reads HTML, XHTML and XML files and writes cleaned up markup. For HTML variants, it detects and corrects many common coding errors and strives to produce visually equivalent markup that is both W3C compliant and works on most browsers. A common use of Tidy is to convert plain HTML to XHTML. For generic XML files, Tidy is limited to correcting basic well-formedness errors and pretty printing.

简单说Tidy是清理HTML代码的,生成干净的符合W3C标准的HTML代码,支持HTML,XHTML,XML。Tidy提供一个库TidyLib,以方便在其他应用中利用Tidy的强大功能。非常幸运,PHP有相应的tidy模块可以使用。

老兄,为什么又是PHP?

呃,这个问题... 惭愧,因为我只会那么点PHP而已 -.-v
不过还好,我这里讲的都不是纯粹的代码,好歹也有些分析的过程,分享这些东西比贴代码有用多了。

PHP中使用Tidy

要在PHP中使用Tidy需要安装Tidy模块,也就是加载tidy.so这个PHP extension,具体过程就略了,纯粹是体力活。最后能在phpinfo()中看到"Tidy support enabled" 就OK。

在这个模块的支持下,PHP中就可以使用Tidy提供的几乎所有的功能。常用的HTML清理是异常轻松的事情,甚至可以生成文档的解析树,像在客户端操作DOM那样的操作HTML的各个Node。下面将会有具体的代码说明,也可以看看PHP官方的相关手册

纠错和过滤的PHP+Tidy实现

上面说了这么多背景素材,似乎太罗唆了,具体的解决问题的代码才最最直接。

1. 简单的纠错实现

function HtmlFix($html)
{

  if(!function_exists('tidy_repair_string'))
    return $html;
  //use tidy to repair html code

  //repair
  $str = tidy_repair_string($html,
                   array('output-xhtml'=>true),
                   'utf8');
  //parse
  $str = tidy_parse_string($str,
                  array('output-xhtml'=>true),
                  'utf8');
  $s = '';

  $nodes = @tidy_get_body($str)->child;

  if(!is_array($nodes)){
    $returnVal = 0;
    return $s;
  }

  foreach($nodes as $n){
    $s .= $n->value;
  }
  return $s;
}

上面的代码就是对可能不规范的XHTML代码进行清理纠错,输出标准的XHTML代码(输入输出都是UTF-8编码)。实现代码不是最精简的,因为为了配合下面的过滤功能,我写的尽可能细致了一些。

2. 高级实现: 纠错+过滤

功能:

  1. XHTML的纠错,输出标准的XHTML代码。
  2. 过滤不安全的代码但是不影响内容展示,只是对style/javascript中不安全代码进行清除。
  3. 对超长字符串插入<wbr>标记以实现浏览器兼容的自动换行功能,相关文章可参考网页中超长文字的断行问题
function HtmlFixSafe($html)
{

  if(!function_exists('tidy_repair_string'))
    return $html;
  //use tidy to repair html code

  // tidy 的参数设定
  $conf = array(
                'output-xhtml'=>true
                ,'drop-empty-paras'=>FALSE
                ,'join-classes'=>TRUE
                ,'show-body-only'=>TRUE
                );

 //repair
  $str = tidy_repair_string($html,$conf,'utf8');
  //生成解析树
  $str = tidy_parse_string($str,$conf,'utf8');

  $s ='';

  //得到body节点
  $body = @tidy_get_body($str);

  //函数 _dumpnode,检查每个节点,过滤后输出
  function _dumpnode($node,&$s){

   //查看节点名,如果是<script> 和<style>就直接清除
    switch($node->name){
    case 'script':
    case 'style':
      return;
      break;
    default:
    }

    if($node->type == TIDY_NODETYPE_TEXT){
      /*
       如果该节点内是文字,做额外的处理:
       过长文字的自动换行问题;
       超链接的自动识别(未实现)
      */
      // insert <wbr>
      $s .= HtmlInsertWbrs($node->value,30,'','&?/\');

      // auto links ??? *** TODO ***
      return;
    }

   //不是文字节点,那么处理标签和它的属性
    $s .= '<'.$node->name;

    //检查每个属性
    if($node->attribute){
      foreach($node->attribute as $name=>$value){

        /*
         清理一些DOM事件,通常是on开头的,
         比如onclick onmouseover等....
         或者属性值有javascript:字样的,
         比如href="javascript:"的也被清除.
         */
        if(strpos($name,'on') === 0
        ||
        stripos(trim($value),'javascript:') ===0
        ){
          continue;
        }

       //保留安全的属性
        $s .= ' '.$name.'="'.HtmlEscape($value).'"';

      }
    }

   //递归检查该节点下的子节点
    if($node->child){

      $s .= '>';

      foreach($node->child as $child){
        _dumpnode($child,$s);
      }

      //子节点处理完毕,闭合标签
      $s .= '</'.$node->name.'>';
    }else{

      /*
       已经没有子节点了,将标签闭合
      (事实上也可以考虑直接删除掉空的节点)
      */
      if($node->type == TIDY_NODETYPE_START)
        $s .= '></'.$node->name.'>';
      else
        /*
          对非配对标签,比如<hr/> <br/> <img/>等
          直接以 />闭合之
          */
        $s .= '/>';
    }
  }
   //函数定义end

  //通过上面的函数 对 body节点开始过滤。
  if($body->child){

    foreach($body->child as $child)
      _dumpnode($child,$s);
  }else
    return '';

  return $s;
}

上面代码中注释应该比较详细,工作原理就配合代码看吧。
更严格的过滤也很容易扩展,比如实现文中的链接自动识别。


一点补充

如果你看过我之前写的网页中超长文字的断行问题,你可能发现上面代码中处理自动换行的函数有所不同:

之前介绍的是HtmlEscapeInsertWbrs(),而上面使用的是HtmlInsertWbrs()。

这里要做一下解释:
HtmlEscapeInsertWbrs()要求输入的字符串未作特殊字符转义的,也就是没有经过htmlspecialchars()对<>&等作&lt;&gt;&amp;处理的。因为函数内部有专门的处理。
而在处理经Tidy处理过后的文字节点的时候,因为Tidy的关系,已经自动把<>&等字符作相应的&lt;&gt;&amp;转义,因此需要用一个专门的函数避免重复的转义,这个函数就是HtmlInsertWbrs(),从名字上就知道它只插入<wbr>标记,不做额外工作。

那么你可能有个问题:
如果<wbr>被插入到HTML标签中间,比如在<div>或者&gt;的中间插入了<wbr>,变成<d<wbr>iv>和&<wbr>gt;,那就会影响到原始信息的展示。

没错,的确是个新问题,不过使用一些技巧就可以有效解决

  1. 因为我们处理的是Tidy得到的文字节点,意味着不可能碰到HTML标签,因此不会碰到在标签中间插入<wbr>的情况。
  2. 对于第二种情况,转义后的字符都是&xxxxx;这样的形式,那么只要在1所有&符号前面都插入<wbr>标记就可以了(注意看调用时的第四个参数),因为下一个<wbr>标记将会插在30(以上面代码中实际调用的第二个参数为例)个字符之后,这个已经2远远大于xxxxx的长度。这样由上面1、2两点可以保证不会插到转义字符的中间。

下面给出HtmlInsertWbrs()的PHP实现:

function HtmlInsertWbrs($str, $n=10,
         $chars_to_break_after='',$chars_to_break_before='')
{
    $out = '';
    $strpos = 0;
    $spc = 0;
    $len = mb_strlen($str,'UTF-8');
    for ($i = 1; $i < $len; ++$i) {
      $prev_char = mb_substr($str,$i-1,1,'UTF-8');
      $next_char = mb_substr($str,$i,1,'UTF-8');
      if (_u_IsSpace($next_char)) {
        $spc = $i;
      } else {
        if ($i - $spc == $n
            ||
           mb_strpos( $chars_to_break_after,
                      $prev_char,0,'UTF-8' )
                   !== FALSE
            ||
           mb_strpos( $chars_to_break_before,
                      $next_char,0,'UTF-8')
                   !== FALSE
         ) {
            $out .= mb_substr($str,$strpos,
                    $i-$strpos,'UTF-8')
                 . '<wbr>';
            $strpos = $i;
            $spc = $i;
          }
      }
    }
    $out .= mb_substr($str,$strpos,$len-$strpos,'UTF-8');
    return $out;
}

...
Ok,先写这么多,相关的资料在文中都有链接。
下次想到再补充。

评论(12)

CSS样式优先级

(转自水木清华)

以前看书做的笔记:

specificity表示了一个样式使用时的优先级
CSS2用3位表示一个样式的specificity
CSS2.1用4位
四条规则:
每个ID选择符,加 0,1,0,0
每个class选择符,每个属性选择符,或者每个伪类,加0,0,1,0
每个元素和伪元素,加0,0,0,1
其他选择符包括全局选择符*都没有加成效果,但它们有specificity,0,0,0,0
一些例子:

h1 {color: red;}  /* 0,0,0,1 */
body h1 {color: green;}  /* 0,0,0,2  (winner)*/

h2.grape {color: purple;}  /* 0,0,1,1 (winner) */
h2 {color: silver;}  /* 0,0,0,1 */

html > body table tr[id="totals"] td ul > li {color: maroon;}  /* 0,0,1,7 */
li#answer {color: navy;}  /* 0,1,0,1  (winner) */

文内的样式specificity为1,0,0,0 始终高于外部定义
特别的,如果一个样式特别重要,可使用!important,它优先于所有其他specificity。
如果!important也发生了冲突,则参考specificity的比较结果,如果specificity冲突则按先后顺序。

关于继承Inheritance
body的background样式可以向上传递给html元素,这是继承的一个例外。
绝大多数盒模型相关属性都不继承,比如margin,padding,background,border等

继承没有specificity,所以继承的优先级低于比如甚至全局选择符的优先级

注:
这篇文章是水木社区上一位朋友发的帖子,并非出自我手。我尽量写一些自己的心得,有些我收藏的比较价值的东西,并且网上一搜结果并不是很泛滥的东西我也会贴些上来的。

跟这个主题相关的还有一些文章可以参考
CSS的优先权
CSS样式的优先级补遗2

评论(0)

网页中超长文字的断行问题

这个应该是比较常见的问题了,通常是连续的一长串无空格的半角字符所引起的,比如比较长的超链接就很有可能把你的页面撑开。网上常见的解决办法就是使用css属性 break-word:break-all; ,但是这个只对IE浏览器有效。

下面介绍一种办法,可以保证各浏览器的兼容。

标记,它的作用是建议浏览器在这个标记处可以断行,只是建议而不是必定会在此处断行,还要根据整行文字长度而定。因此只要在连续的文字中间适当的插入若干标记就能解决断行问题。

我最初看到这个解决办法是在Gmail的代码中,它是这么实现的:(All rights reserved by Google. Please refer to each Please read the disclaimer about the limitations of the information provided here. HIV+ owned and operated. Buy Combivir com: The Internet publication with accurate, timely and cutting-edge information on treatment and vaccines for HIV, AIDS and chronic hepatitis B and hepatitis CA collection of patient education fact sheets on HIV/AIDS treatments and conditions, in English and Spanish. 24 hours/7Full prescribing information from RxList. )

JS实现

function HtmlEscapeInsertWbrs(str, n, chars_to_break_after,
                              chars_to_break_before)
{
    var out = '';
    var strpos = 0;
    var spc = 0;
    for (var i = 1; i < str.length; ++i) {
        var prev_char = str.charAt(i - 1);
        var next_char = str.charAt(i);
        if (IsSpace(next_char)) {
            spc = i;
        } else {
            if (i - spc == n
            || chars_to_break_after.indexOf(prev_char) != -1
            || chars_to_break_before.indexOf(next_char) != -1)
            {
                out += HtmlEscape(str.substring(strpos, i))
                      + '';
                strpos = i;
                spc = i;
            }
        }
    }
    out += HtmlEscape(str.substr(strpos));
    return out;
}
/////
function IsSpace(ch)
{
    return (" trn".indexOf(ch) >= 0);
}
function HtmlEscape(str){
    return
        str.replace(/&/g,"&").replace(//g,">").replace(/\"/g,""");
}

说明: 函数已经帮你处理了Html敏感的符号(&<>),用了这个函数并不是说字符串显示的时候就会在某个点断行,只是在其中设置了可能的断行点()标记,在显示宽度不够的时候的情况下才指示浏览器做出断行。


用法: 参数说明
str: 你要处理的原始字符串
n: 每行最多多少个字符
chars_to_break_after: 一个字符串,比如"-:_",就会在这些字符后面发生断行(如果有断行必要) 如果不需要特别设置,那么使用空字符串 ""就行了

chars_to_break_before: 功能类似于上面这个, 没有特殊需要就设置成 "" 就可以了

函数是JavaScript的实现, 我根据这个做了一个PHP的实现,它工作得很好。

PHP实现

/*
 * support UTF-8 only,
 * ** the function return HTML Format string **
 */
function HtmlEscapeInsertWbrs($str, $n=10,
         $chars_to_break_af PrevacidWhat you may not have been told on the drug PrevacidExplaining what PrevacidFind medical information for PrevacidDepicts the medication lansoprazole (Prevacid, PrevacidPosted on Nov 6th 2008 1:30PM by Kelly Wilson Dear AOL Hometown userAccurate, FDA approved PrevacidHow To Use PrevacidHow To Use PrevacidPrevacidPrevacidSide Effects. Prevacid (lansoprazole) suspension forPrevacid is a medication used to treat gastroesophageal reflux disease (GERD) and other conditions. Buy Prevacid Generic and branded prescription drugs are available at MedStore. Prevacid Delayed Release Oral Suspension is designed for people who have acid-induced stomach problems and relieves symptomsDepicts the medication lansoprazole (Prevacid, Prevacid SoluTab), a drug used Lansoprazole is used for treating ulcers of the stomach and duodenum, gastroesophagealFind medical information for Prevacid Oral including side effects, drug interactions, images and pictures, medication uses, warnings, user ratings and reviews. ter='',$chars_to_break_before='')
{
    $out = '';
    $strpos = 0;
    $spc = 0;
    $len = mb_strlen($str,'UTF-8');
    for ($i = 1; $i < $len; ++$i) {
      $prev_char = mb_substr($str,$i-1,1,'UTF-8');
      $next_char = mb_substr($str,$i,1,'UTF-8');
      if (_u_IsSpace($next_char)) {
        $spc = $i;
      } else {
        if ($i - $spc == $n
         || mb_strpos( $chars_to_break_after,
            $prev_char,0,'UTF-8' ) !== FALSE
         || mb_strpos( $chars_to_break_before,
            $next_char,0,'UTF-8')  !== FALSE )
          {
            $out .= HtmlEscape(
                mb_substr($str,$strpos, $i-$strpos,'UTF-8')
                       ) . '';
            $strpos = $i;
            $spc = $i;
          }
      }
    }
    $out .= HtmlEscape(
             mb_substr($str,$strpos,$len-$strpos,'UTF-8')
               );
    return $out;
}
/////
function _u_IsSpace($ch)
{
  return mb_strpos(" trn",$ch,0,'UTF-8') order hydrea. HYDREA (hydroxyurea capsules, USP) is an antineoplastic agent, available for tumor response to HYDREA has been demonstrated in HYDREA occasionally mayHydra (Greek: Žδα, pronounced [ˆiðra]) is one of the Saronic Islands of Greece, located in the Aegean Sea between the Saronic Gulf and the Argolic Gulf. Buy Hydrea The glossary definition of the term HydreaPhysician reviewed HydreaADVERSE REACTIONS, and DOSING AND ADMINISTRATION sections of the HYDREA (hydroxyurea capsules, HYDREAGeneric hydreaHYDREAThe FDA has approved revisions to the safety labeling for hydroxyurea capsules (Hydrea and Droxia) and intravenous Rho(D) human immune globulin (WinRho SDF)hydroxyurea n. Reducing the number of painful episodes and blood transfusionsindications contra-indications dosage side-effects pregnancy overdose identification patient information hydrea capsulesHydrea (Oral) - Hydrea for Leukemia - Medicine Hydrea Home > Prescription Drug Reference > Hist - Hydr > Hydrea Drug and Prescription Information, Side Effects, Use, and DosageHydrea,DroxiaBuy Hydrea (Hydroxyurea) online without prescription on discount prices.  !== FALSE;
}
function HtmlEscape($s)
{
  return htmlspecialchars($s);
}

同样,该函数会对传入的字符串中的特殊字符做转义处理(htmlspecialchars()),因此传入的字符串必须是原始的(未经htmlspecialchars()处理过的),函数返回后的结果可以直接在网页中输出。
参数使用方法跟上面的JS版本类似,我就不罗唆了。

你可以改写成其他语言的,到时候也记得发给我一份 :)

评论(16)

如何用Squid来实现Ajax跨域代理

什么是Ajax跨域代理?

玩Ajax的应该知道我在说什么:) 简单说就是因为浏览器的安全限制,你不能直接获取你站点以外的xml文档。

为什么用Squid来做?

你完全可以自己写一个代理小程序,比如用php,这方面的资料网上很多。
Squid是一个应用非常广泛、功能强大的代理服务器软件,用它自然是为了获得高效。

需要哪些软件?

Lighttpd(Apache)、Squid、squirm。 我这里以lighttpd为例,你完全可以用apache来代替。
这里介绍一下squirm,这是一款为squid量身定做的redirector程序,支持 正规表达式 ,至于什么是redirector下面的工作原理你会知道它的作用。
系统平台:理论上支持上述软件的应该都可以(比如选择常见的linux),我这里以freebsd为例。

工作原理

用Lighttpd(Apache)的proxy模块作前端代理,把特定url的请求发送到squid,比如把 /service/proxy/*/http://othersite.com/abc.xml 这样的请求发送给squid来处理。

squid通过squirm这个redirector对url进行修正(相当于url rewrite),通过squirm的配置文件我们可以把上述url地址重定向为 http://othersite.com/abc.xml ,这个过程对浏览器是透明的完全由squid完成。squid获取 http://othersite.com/abc.xml 后返回给浏览器,这样我们就实现了跨域,在Ajax应用中你如果要获取其他站点的内容就在url前加上 /service/proxy/*/ 即可。

关键配置

相关软件的基本配置网上很容易找到参考,我就不罗嗦了,下面给出关键的配置。

Lighttpd - lighttpd.conf,比如我们的squid将工作在6666端口,就作如下配置

$HTTP["url"] =~ "^/service/proxy/" {
    proxy.server = (
        "" => (
                   (
                        "host" => "127.0.0.1",
                        "port" => 6666
                    )
                )
    )
}

Squid - squid.conf

http_port 6666
redirect_program /usr/local/bin/squirm
redirect_children 5
redirect_rewrites_host_header on
httpd_accel_host virtual
httpd_accel_with_proxy on
httpd_accel_uses_host_header on

squirm
- squirm.conf 主要指定redirector的匹配规则文件的位置

begin
network 0.0.0.0/0
log /var/squid/logs/squirm-private-match.log
abort-log /var/squid/logs/squirm-private-abort.log
pattern common.patterns all
end

- common.patterns 这里的匹配规则文件是 common.patterns

regex ^.*/service/proxy/\*/(.*)$        \1

...
ok,that's all.

相关链接:
Squid: http://www.squid-cache.org
Lighttpd: http://www.lighttpd.net
Apache: http://www.apache.org
Squirm: http://squirm.foote.com.au

注:原文曾发布在http://www.mipang.com/groups/tiandi/t.331.d13577b5f3.htm

评论(0)

AJAX应用中怎样确保得到XML DOM对象?

使返回的xml数据能够作为XML DOM对象来用,需要这么几件事情:

1、服务器返回的头部信息需要 设置 Content-Type: text/xml

2、返回的xml结构中需要有个documentElmement节点,这样可以保证各浏览器之间的兼容。举例来说:
(建议你客户端和服务器端全部使用UTF-8编码,减少因编码问题引起的莫名奇妙问题)

<?xml version="0.1" encoding="UTF-8"?>
<res>
  <data><![CDATA[abc123]]></data>
</res>

这里 res就是documentElement

3、以上面的xml为例,客户端收到responseXML对象后,首先

var doc = responseXML.documentElement; //得到 res,这步很重要
var d = doc.getElementsByTagName('data')[0];
alert( getNodeValue(d) ); //  show 'abc123'

//----------------------
function getNodeValue(node)
{
  if(node && node.hasChildNodes()){
    //return node.firstChild.nodeValue;
    var s="";
    //Mozilla has many textnodes with a size of 4096 chars
    // each instead of one large one.
    //They all need to be concatenated.
    for(var j=0;j<node.childNodes.length;j++){
      s+=new String(node.childNodes.item(j).nodeValue);
    }
    return s;
  }else
    return "";
}


评论(1)

生成XML文档时CDATA段中含有]]>怎么办?

这是个有意思的问题,包含在CDATA标签<![CDATA[ ... ]]>之间的内容会被XML解析器忽略,这样就不需要对内容中出现的 <>&等字符进行转义(&lt;&gt;&amp;)。

但是内容中一旦出现]]>,就会导致XML解析失败,因为CDATA不允许嵌套。
解决的办法不止一个,我采用把 ]]>拆开放入两个CDATA中的简单办法,下面是PHP的实现:

function XmlCDATAStr($s)
{
  $a = explode(']]>',$s);
  return XmlSafeStr(implode(']]]]><![CDATA[>',$a));
}

上面用到了前文提到的XmlSafeStr()函数来过滤非法的XML字符。

有更好的办法请一定告诉我 :)

评论(15)

过滤XML中遇到的非法字符

XML规范规定的非法字符有:

/*
  0x00 - 0x08
  0x0b - 0x0c
  0x0e - 0x1f
*/

含有这些字符的XML文档在解析的时候就会报错,因此输出的时候需要进行过滤。

PHP的实现:

function XmlSafeStr($s)
{
  /*
    0x00 - 0x08
    0x0b - 0x0c
    0x0e - 0x1f
  */
  return preg_replace("/[x00-x08x0b-x0cx0e-x1f]/",'',$s);
}

当然,如果有现成的PHP模块提供类似的功能,请大家告诉我 :P

评论(0)

1