代码之家  ›  专栏  ›  技术社区  ›  Gary Willoughby

在PHP中使用正则表达式选择性地替换标签外的单词?

  •  0
  • Gary Willoughby  · 技术社区  · 14 年前

    我有一段文字,我想用php替换一些单词(preg_replace)。以下是一段文本示例:

    This lesson addresses rhyming [one]words and ways[/one] that students may learn to identify these words. Topics include learning that rhyming words sound alike and these sounds all come from the [two]ending of the words[/two]. This can be accomplished by having students repeat sets of rhyming words so that they can say them and hear them. The students will also participate in a variety of rhyming word activities. In order to demonstrate mastery the students will listen to [three]sets of words[/three] and tell the teacher if the words rhyme or not.

    如果你注意到“单词”这个词有很多出现。我想取代所有那些 不要 出现在任何带有“birds”字样的标签中。所以看起来是这样的:

    This lesson addresses rhyming [one]words and ways[/one] that students may learn to identify these birds. Topics include learning that rhyming birds sound alike and these sounds all come from the [two]ending of the words[/two]. This can be accomplished by having students repeat sets of rhyming birds so that they can say them and hear them. The students will also participate in a variety of rhyming word activities. In order to demonstrate mastery the students will listen to [three]sets of words[/three] and tell the teacher if the birds rhyme or not.

    您会使用正则表达式来完成这个任务吗?
    罐头 正则表达式可以做到这一点?

    1 回复  |  直到 13 年前
        1
  •  1
  •   cletus    14 年前

    您所拥有的标记没有定义一种常规语言,因此,正则表达式不能很好地实现这一点。我认为你能做的最好的事情就是移除所有的标签(用其他东西替换它们),用“birds”替换“words”,然后把内容放回原处。

    $str = preg_replace_callback('!\[one\].*?\[/one\]!s', 'hash_one', $input);
    $str = str_replace('words', 'birds', $str);
    $output = preg_replace_callback('!:=%\w+%=:!', 'replace_one', $str);
    
    $hash = array();
    
    function hash_one($matches) {
      global $hash;
      $key = ':=%' . md5($matches[0]) . '%=:'; // to ensure this doesn't occur naturally
      $hash[$key] = $matches[0];
      return $key;
    }
    
    function replace_one($amtches) {
      global $hash;
      $ret = $hash[$matches[0]];
      return $ret ? $ret : $matches[0];
    }