【问题标题】:Tagging phrases in paragragh在段落中标记短语
【发布时间】:2010-06-24 09:03:24
【问题描述】:

我正在使用 PHP,我希望在我的文本中创建指向网站其他部分的链接,例如:

I fell into the media industry aged 30, when David Mansfield, now on the board of
Ingenious Media, gave me my first break at Thames TV. From there, I worked at the
(now-defunct) Sunday Correspondent and IPC, before joining TDI, which became Viacom
and then CBS Outdoor. After 12 years in outdoor, I spent a year out doing overseas
outdoor consultancy work in Russia, Dubai and Spain, as well as launching the media 
CRM business, Media By Permission. I have been lucky enough to work across a range of 
media, but outdoor would definitely be my specialist subject on 'Mastermind'.

我想将Ingenious Media 链接到一个关于Ingenious Media 的页面,但我还想将所有提及Media 的页面链接到一个媒体相关页面。

显然我不想将Media这个词链接到Ingenious Media

如果不对某些单词进行双重链接,我怎么能这样做呢?

提前致谢

【问题讨论】:

    标签: php regex string strpos find-occurrences


    【解决方案1】:

    第 1 步。创建一个包含您要“标记”的实体名称的新数组,并将最长的实体名称排序为最短的实体名称。

    步骤 2. 遍历此数组并将文本中出现的每个实体替换为唯一标记(例如 ## . rand(100, 999) * rand(100, 999))。我们这样做是为了避免在构成另一个实体的一部分的实体周围创建链接。

    第 3 步。创建链接并将其存储在另一个数组中,其中数组中每个条目的键是唯一令牌,值是您刚刚创建的链接。

    步骤 4. 遍历 links 数组并将文本中的标记替换为与数组中的标记对应的链接。

    【讨论】:

      【解决方案2】:

      我不确定这是否可以使用正则表达式。我会这样做:

      1. 搜索词组
      2. 检查短语是否在链接内(如果它是开始标签而不是你可能不在里面,如果它是eding标签你在里面,则向右搜索标签a)
      3. 如果你不在里面替换

      【讨论】:

        【解决方案3】:

        也许如果你使用贪婪的正则表达式从一个阶段尽可能多地匹配。看看那些链接http://www.exampledepot.com/egs/java.util.regex/Greedy.htmlhttp://www.regular-expressions.info/repeat.html

        【讨论】:

          【解决方案4】:
          $string = '...your string from above....';
          
          // Here we replace only "Media" when there is no "Ingenious " in front of it.
          $string = preg_replace('#(?<!Ingenious )Media#', '<a href="media.html">Media</a>', $string);
          
          // Here don't need to use a regex...
          $string = str_replace('Ingenious Media', '<a href="ingenious_media.html">Ingenious Media</a>', $string);
          echo $string;
          

          我敢肯定,有一个更好的正则表达式,因为总是有;) 但这样它就可以工作,只是测试了它:)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-11-23
            • 2014-01-10
            • 2018-01-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-12-11
            相关资源
            最近更新 更多