2010-03-31 2 views
0

텍스트 단락이 있고 PHP (preg_replace)를 사용하여 일부 단어를 바꿔야합니다. 다음은 텍스트의 샘플 조각입니다 :PHP의 정규 표현식을 사용하여 태그 외부의 단어를 선택적으로 대체 하시겠습니까?

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

태그는 정규 언어를 정의하지 않으므로 정규 표현식이 제대로 작동하지 않습니다. 내가 할 수있는 최선의 방법은 모든 태그를 제거하고 (다른 태그로 대체), "단어"를 "새"로 바꾸고 내용을 다시 넣는 것입니다.

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

하, 이것은 실제로 내가 사용한 방법입니다! –