1

我有以下故事“另一个 Feed 在 Facebook 的照片上分享了非营利组织。 ”我想用链接替换它的标签。

facebook api 数据故事和story_tags

                    [story] => Another Feed shared Non-Profits on Facebook's photo.
                    [story_tags] => Array
                        (
                            [0] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 1.7153566624E+14
                                            [name] => Another Feed
                                            [offset] => 0
                                            [length] => 12
                                            [type] => page
                                        )

                                )

                            [20] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 41130665917
                                            [name] => Non-Profits on Facebook
                                            [offset] => 20
                                            [length] => 23
                                            [type] => page
                                        )

                                )

                        )

如果我用 str_ireplace 替换故事标签,那么有可能两个不同的标签可以具有相同的名称,所以它不会很好玩。

如果我用 substr_replace(...) 替换它,那么在替换后故事的长度会变得更长,所以新标签不能很好地与它一起使用。

用故事情节替换故事标签的最佳方法是什么?我确定人们已经这样做了,但找不到它。

4

1 回答 1

1

Have a look here at my implementation:

  public function mapMentions($message, $tags) {
    if (empty($tags)) {
      return $message;
    }

    $offsetBuffer = 0;

    foreach (json_decode($tags, true) as $tag) {
      $link = $this->Html->link($tag['name'], $tag['link'], ['target' => '_blank']);
      $message = substr_replace($message, $link, $tag['offset'] + $offsetBuffer, $tag['length']);
      $offsetBuffer += (strlen($link) - $tag['length']);
    }

    return $message;
  }
  1. First, you need the length of the generated link (graph.facebook.com/ID)
  2. Now, you need to save the the difference between old length and new link length to a temp variable (in my case "offsetBuffer").
  3. In the loop append the offsetBuffer to the old offset.

Voila! ;)

于 2014-06-02T13:36:27.350 回答