2

我有一个国家数组,键是国家代码,值是国家名称,现在我有一个字符串,由用户发布,我想查找字符串中是否有国家 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);

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

请记住,它不应该区分大小写,一些用户可能会发布加拿大或加拿大

谢谢

4

2 回答 2

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:我由 DOMDocument 编写,在 Html 中运行良好

 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('#<!–[^\[].+–&gt;#', '', $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
于 2013-05-06T16:34:32.757 回答
0

我自己写的,这是迄今为止最好的:

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

谢谢你们

于 2013-05-06T19:25:06.367 回答