bir teklif sonra bir harf yazmak için preg_replace

6 Cevap php

Bu gibi isimler var:

$str = 'JAMES "JIMMY" SMITH'

Ben bu döndüren, ucwords sonra, strtolower çalıştırın:

$proper_str = 'James "jimmy" Smith'

Ben ilk harfi bir çift alıntı olduğu kelimelerin ikinci mektubu yararlanmak istiyorum. İşte sıradanifade bulunuyor. Bu çalışmıyor strtoupper görünüyor - Regexp sadece değişmeden orijinal ifadeyi döndürür.

$proper_str = preg_replace('/"([a-z])/',strtoupper('$1'),$proper_str);

Herhangi bir ipucu? Teşekkürler!

6 Cevap

preg_replace_callback kullanın - Ama yerine bir anonim işlevini kullanın, ekstra bir adlandırılmış işlev eklemek için ihtiyacım yok.

$str = 'JAMES "JIMMY" SMITH';
echo preg_replace_callback('!\b[a-z]!', function ($matches) {
     return strtoupper($matches[0]);
}, $str);

Kullanımı /e php sonraki sürümü (5.5) amortismana tabi olacak

Böyle bir şey hile yapabilir:

preg_replace("/(\w+)/e", "ucwords(strtolower('$1'))", $proper_str);

Ben özel ucwords() function parçası olarak, regex olmadan bunu. Fazla iki tırnak varsayarak dize görüntülenir:

$parts = explode('"', $string, 3); 
if(isset($parts[2])) $string = $parts[0].'"'.ucfirst($parts[1]).'"'.ucfirst($parts[2]);            
else if(isset($parts[1])) $string = $parts[0].'"'.ucfirst($parts[1]);   

Bunu yapmanız gerekir:

$proper_str = 
    preg_replace_callback(
        '/"([a-z])/',
        function($m){return strtoupper($m[1]);},
        $proper_str
);

Güvenlik nedenleriyle "eval ()" kullanın should'nt.

Anyway, the patern modifier "e" is deprecated. See : PHP Documentation.