簡體   English   中英

使用PHP中的正則表達式選擇性地替換標記之外的單詞?

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

我有一段文字,我想用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.

您會使用正則表達式來做到這一點嗎?
正則表達式可以做到這一點?

您使用的標簽未定義常規語言,因此常規表達式不適用於此。 我認為您可以做的最好的事情是刪除所有標簽(用其他東西替換它們),用“ 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