2013-10-25 63 views
0

使用offset屬性讓message_tags聯我得到來自Facebook的API這篇文章對象:在Facebook的API

{ 
"id"=>"XXX", 
..., 
"message"=>"abcd efg hijkl mn The New York Times opqr", 
"message_tags"=>{ 
    "18"=>[{ 
     "id"=>"5281959998", 
     "name"=>"The New York Times", 
     "type"=>"page", 
     "offset"=>18, 
     "length"=>18 
     }] 
    }, 
... 
} 

我怎樣才能使軌道Facebook粉絲專頁喜歡用偏移&長度屬性的鏈接?結果會是這樣的:

abcd efg hijkl mn <a href="www.facebook.com/5281959998">The New York Times</a> opqr 

回答

0

我不得不這樣做,但在PHP中。這是我的解決方案:

/** 
* Get message HTML 
* 
* @param string $text The message text 
* @param array $tags The tags array 
* @return string HTML message string with linked tags 
*/ 
public static function getMessageHtml($text, $tags) { 
    $doc = new DOMDocument; 
    $doc->appendChild($doc->createTextNode($text)); 
    if (is_array($tags)) { 
     foreach ($tags as $tag) { 
      $tag = $tag[0]; 
      $start = 0; 
      foreach ($doc->childNodes as $child) { 
       if ($tag['offset'] < $start + strlen($child->nodeValue)) { 
        $meat = $child->splitText($tag['offset'] - $start); 
        $tail = $meat->splitText($tag['length']); 
        $a = $doc->createElement('a'); 
        $a->setAttribute('href', '//facebook.com/' . $tag['id']); 
        $a->setAttribute('title', $tag['name']); 
        $meat->parentNode->replaceChild($a, $meat); 
        $a->appendChild($meat); 
        break; 
       } 
       $start += strlen($child->nodeValue); 
      } 
     } 
    } 
    return trim($doc->saveHTML()); 
} 

這在我所有的測試案例,到目前爲止的工作,但它可能是不可靠的,如果標籤重疊或嵌套。我不確定Facebook是否會返回這樣的標籤。

希望您可以輕鬆地將此端口移植到Ruby。