我有一段文字,我想用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.
你会使用正则表达式来实现这个目标吗? 可以一个正则表达式来完成这个吗?
答案 0 :(得分:1)
您拥有的标签没有定义常规语言,因此正则表达式不适用于此。我认为你能做的最好的事情是删除所有标签(用其他东西替换它们),用“鸟”代替“单词”,然后把内容放回去。
$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];
}