从字符串中查找和替换country

时间:2013-05-06 16:24:38

标签: php preg-replace

我有一个国家/地区的数组,关键是国家/地区代码,值是国家/地区名称,现在我有一个字符串,由用户发布,我想查找字符串是否有在其中的国家n用

替换它
<span class="country">$1</span>

让它更清晰:让我说我有这样的文字:

Canada is a cold place

我希望它是:

<span class="country">canada</span> is a cold place

我使用我的国家/地区数组来查找和重新发布。

背后的原因是我想使用微格式,所以我需要从字符串中提取特定的文本。

我有类似的preg_replaces代码

$style  = array(
                    '/\[b\](.*)?\[\/b\]/isU'            => '<b>$1</b>',
                    '/\[i\](.*)?\[\/i\]/isU'            => '<i>$1</i>',
                    '/\[u\](.*)?\[\/u\]/isU'            => '<u>$1</u>',
                    '/\[em\](.*)?\[\/em\]/isU'      => '<em>$1</em>',
                    '/\[li\](.*)?\[\/li\]/isU'      => '<li>$1</li>',
                    '/\[code\](.*)?\[\/code\]/isU'  => '<div class="tx_code">$1</div>',
                    '/\[q\](.*)?\[\/q\]/isU'    => '<q>$1</q>',
                    '/[\r\n]{3}+/'              => "\n"
                    );  

$text = preg_replace(array_keys($style),array_values($style),$text);

哪个有效,我需要这样的东西。

  
    

请注意,它不应区分大小写,有些用户可能会发布加拿大或加拿大

  

感谢

2 个答案:

答案 0 :(得分:1)

试试这个

  function findword($text,array $List){
         foreach($List as $Val)
            $pattern['%([^\da-zA-Z]+)'.$Val.'([^\da-zA-Z]+)%si'] = '<span class="country">'.$Val.'</span>';
         $text = preg_replace(array_keys($pattern), array_values($pattern), ' '.$text.' ');
         return $text;
  }
  echo findword('Canada is a cold place',array('Canada'));

输出:

<span class="country">Canada</span>is a cold place

修改:如果您想要替换文字中的所有匹配字,可以使用此

  function findword($text,array $List){
         foreach($List as $Val)
            $pattern['~'.$Val.'~si'] = '<span class="country">'.$Val.'</span>';
         $text = preg_replace(array_keys($pattern), array_values($pattern), ' '.$text.' ');
         return $text;
  }
  echo findword('Canadaisacold place',array('Canada'));

输出:

<span class="country">Canada</span>isacold place

Edit2:我用Html

中的DOMDocument写得很好
 class XmlRead{    
  static function Clean($html){
   $html=preg_replace_callback("~<script(.*?)>(.*?)</script>~si",function($m){
      //print_r($m);
     // $m[2]=preg_replace("/\/\*(.*?)\*\/|[\t\r\n]/s"," ", " ".$m[2]." ");
      $m[2]=preg_replace("~//(.*?)\n~si"," ", " ".$m[2]." ");
      //echo $m[2];
      return "<script ".$m[1].">".$m[2]."</script>";
      }, $html);
  $search = array(
      "/\/\*(.*?)\*\/|[\t\r\n]/s" => "",
      "/ +\{ +|\{ +| +\{/" => "{",
      "/ +\} +|\} +| +\}/" => "}",
      "/ +: +|: +| +:/" => ":",
      "/ +; +|; +| +;/" => ";",
      "/ +, +|, +| +,/" => ","
      );
      $html = preg_replace(array_keys($search), array_values($search), $html);
    preg_match_all('!(<(?:code|pre|script).*>[^<]+</(?:code|pre|script)>)!',$html,$pre);
    $html = preg_replace('!<(?:code|pre).*>[^<]+</(?:code|pre)>!', '#pre#', $html);
    $html = preg_replace('#<!–[^\[].+–>#', '', $html);
    $html = preg_replace('/[\r\n\t]+/', ' ', $html);
    $html = preg_replace('/>[\s]+</', '><', $html);
    $html = preg_replace('/\s+/', ' ', $html);
    if (!empty($pre[0])) {
        foreach ($pre[0] as $tag) {
            $html = preg_replace('!#pre#!', $tag, $html,1);
        }
    }
    return($html);
}
function loadNprepare($content,$encod='') {
   $content=self::Clean($content);
   //$content=html_entity_decode(html_entity_decode($content));
  // $content=htmlspecialchars_decode($content,ENT_HTML5);
   $DataPage='';
   if(preg_match('~<body(.*?)>(.*?)</body>~si',$content,$M)){
      $DataPage=$M[2];
   }else{
      $DataPage =$content;
   }
   $HTML=$DataPage;
   $HTML="<!doctype html><html><head><meta charset=\"utf-8\"><title>Untitled Document</title></head><body>".$HTML."</body></html>";
   $dom= new DOMDocument; 
   $HTML = str_replace("&", "&amp;", $HTML);  // disguise &s going IN to loadXML() 
  // $dom->substituteEntities = true;  // collapse &s going OUT to transformToXML() 
   $dom->recover = TRUE;
   @$dom->loadHTML('<?xml encoding="UTF-8">' .$HTML); 
   // dirty fix
   foreach ($dom->childNodes as $item)
    if ($item->nodeType == XML_PI_NODE)
      $dom->removeChild($item); // remove hack
    $dom->encoding = 'UTF-8'; // insert proper
    return $dom;
}
function GetBYClass($Doc,$ClassName){
    $finder = new DomXPath($Doc);
    return($finder->query("//*[contains(@class, '$ClassName')]"));
}
function findword($text,array $List){
     foreach($List as $Val)
        $pattern['%(\#)?([^\da-zA-Z]+)'.$Val.'([^\da-zA-Z]+)%si'] = '<span class="country">'.$Val.'</span>';
     $text = preg_replace(array_keys($pattern), array_values($pattern), ' '.$text.' ');
     return $text;
}
function FindAndReplace($node,array $List) {
     if($node==NULL)return false;    
     if (XML_TEXT_NODE === $node->nodeType || XML_CDATA_SECTION_NODE === $node->nodeType) {
         $node->nodeValue=$this->findword($node->nodeValue,$List);
         return;
     }else{
         if(is_object($node->childNodes) or is_array($node->childNodes)) {
           foreach($node->childNodes as $childNode) {
              $this->FindAndReplace($childNode,$List);
           }
         }
     }

}
function DOMinnerHTML($element) 
{ 
   $innerHTML = ""; 
   $children = $element->childNodes; 
   foreach ($children as $child) 
   { 
      $tmp_dom = new DOMDocument(); 
      $tmp_dom->appendChild($tmp_dom->importNode($child, true)); 
      $innerHTML.=trim($tmp_dom->saveHTML()); 
   } 
   $innerHTML=html_entity_decode(html_entity_decode($innerHTML));
   return $innerHTML; 
} 
function DOMRemove(DOMNode $from) {

    $from->parentNode->removeChild($from);    
 }

}
$XmlRead=new XmlRead();
$Doc=$XmlRead->loadNprepare('<a href="?Canada">Canada</a> is a cold place');
$XmlRead->FindAndReplace($Doc,array('Canada'));
$Body=$Doc->getElementsByTagName('body')->item(0);
echo $XmlRead->DOMinnerHTML($Body);

输出

<a href="?Canada"><span class="country">Canada</span></a>is a cold place

答案 1 :(得分:0)

我写了自己的,到目前为止是最好的:

    if($microformat){
        foreach ($this->countries as $co){
        $text = preg_replace('/(\#)?\b'.$co.'\b/isU','<span class="country">$0</span>',$text);
        }
    }

谢谢大家