简体   繁体   English

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

[英]Selectively replacing words outside of tags using regular expressions in PHP?

I have a paragraph of text and i want to replace some words using PHP (preg_replace). 我有一段文字,我想用PHP(preg_replace)替换一些单词。 Here's a sample piece of text: 这是一段示例文本:

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.

If you notice there are many occurances of the word 'words'. 如果您注意到“单词”一词的出现次数很多。 I want to replace all the occurances that don't occur inside any of the tags with the word 'birds'. 我想用“ birds”一词替换所有在任何标签内发生的事件。 So it looks like this: 所以看起来像这样:

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.

Would you use regular expressions to accomplish this? 您会使用正则表达式来做到这一点吗?
Can a regular expression accomplish this? 正则表达式可以做到这一点?

The tags you have don't define a regular language and thus regular expressions won't work well for this. 您使用的标签未定义常规语言,因此常规表达式不适用于此。 The best I think you can do is remove all the tags (replace them with something else), replace "words" with "birds" and then put the content back. 我认为您可以做的最好的事情是删除所有标签(用其他东西替换它们),用“ 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM