Seçici PHP düzenli ifadeler kullanarak etiketleri dışında kelimeler yerine?

1 Cevap php

Ben metin bir paragraf var ve ben PHP (preg_replace) kullanarak bazı kelimeleri değiştirmek istiyor. İşte metninin örnek bir parça bulunuyor:

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.

Eğer fark ederseniz kelime 'kelimeler' birçok olay vardır. I don't kelime 'kuşlar' ile etiketleri herhangi içinde gerçekleşen tüm tekrarlarını değiştirmek istiyor. Yani bu gibi görünüyor:

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?

1 Cevap

Var etiketleri düzenli bir dili tanımlamak yoktur ve bu nedenle düzenli ifadeler bunun için iyi çalışmaz. Ben bunu düşünüyorum iyi "kuşlar" ile tüm etiketleri (başka bir şey ile değiştirin), "kelime" yerine kaldırmak ve sonra tekrar içerik koymak olduğunu.

$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];
}