Düzenli İfade Yardım - parantez içinde Konsollar

5 Cevap php

Ben şöyle bir dize ile sıralayabilirsiniz bir işlevi geliştirmeye çalışıyorum:

Donny went to the {park|store|{beach with friends|beach alone}} so he could get a breath of fresh air. 

Ne yapmak niyetinde {} patterns where there is no { or } inside the {} için özyinelemeli metin arama, bu yüzden sadece içteki sandviç metin süreci tekrarlayarak, ben o içeriği diziye bir php çalıştırmak ve rastgele birini seçmek nerede, seçilinceye kadar olduğunu bütün dize tam bir cümle gösteren çözümlenir.

Ben sadece olsa normal ifadeler etrafında başımı sarmak olamaz.

Herhangi bir yardım için teşekkür ederiz!

5 Cevap

Düzenli ifadeler özyinelemeli malzeme ile de anlaşma yok, ama PHP yapar:

$str = 'Donny went to the {park|store|{beach with friends|beach alone}} so he could get a breath of fresh air.';

echo parse_string($str), "\n";

function parse_string($string) {
    if ( preg_match('/\{([^{}]+)\}/', $string, $matches) ) {
        $inner_elements = explode('|', $matches[1]);
        $random_element = $inner_elements[array_rand($inner_elements)];
        $string = str_replace($matches[0], $random_element, $string);
        $string = parse_string($string);
    }
    return $string;
}

Bunun arkasında matematik teorisi hakkında bilmek ;-/ ama pratikte oldukça kolay etmeyin. Denemek

$text = "Donny went to the {park|store|{beach with friends|beach alone}} so he could get a breath of fresh air. ";

function rnd($matches) {
    $words = explode('|', $matches[1]);
    return $words[rand() % count($words)];
}

do {
    $text = preg_replace_callback('~{([^{}]+)}~', 'rnd', $text, -1, $count);
} while($count > 0);

echo $text;

Regexes are not capable of counting ve bu nedenle güvenilir bir parantez eşleşen bulamıyorum.

Nelere ihtiyacınız grammar olduğunu.

See this related question.

$str="Donny went to the {park|store|{beach {with friends}|beach alone}} so he could get a breath of fresh air. ";
$s = explode("}",$str);
foreach($s as $v){
 if(strpos($v,"{")!==FALSE){
  $t=explode("{",$v);
  print end($t)."\n";
 }
}

çıktı

$ php test.php
with friends

Bir lexer / Çözümleyici ile bu yapabilirdi. PHP herhangi bir seçenek bilmiyorum (ama PHP XML ayrıştırıcıları vardır beri, hiç şüphe jenerik ayrıştırıcılarda vardır). Öte yandan, sen ne yapmak istiyorsun çok karmaşık değildir. PHP dizeleri (substring, vb) kullanarak muhtemelen birkaç özyinelemeli fonksiyonlar bu yapabilirdi.

Daha sonra nihayet bir basit dilbilgisi PHP ile bir MadLibz jeneratör yaratmış olacaktır. Pretty cool.