str_replace sorunu

2 Cevap

Ben URL içine başlık verileri değiştirmek için çalışıyorum. Ben $ başlığı olsun aşağıdaki dinamik veri "tarihine" den başlayarak tüm metin kapalı kurtulmak gerekir:

New York deadline May 14th, 2010 (urgent)
New Hampshire deadline May 19th, 2010
New Jersey deadline

I expect the result should be like this
new-york
new-hampshire
new-jersey

İşte ben denedim kodu

$newurl = strip_tags(str_replace("deadline","","$title"));
$code_entities_match = array( '&quot;' ,'!' ,'@' ,'#' ,'$' ,'%' ,'^' ,'&' ,'*' ,'(' ,')' ,'+' ,'{' ,'}' ,'|' ,':' ,'"' ,'<' ,'>' ,'?' ,'[' ,']' ,'' ,';' ,"'" ,',' ,'.' ,'_' ,'/' ,'*' ,'+' ,'~' ,'`' ,'=' ,' ' ,'---' ,'--','--');
$code_entities_replace = array('' ,'-' ,'-' ,'' ,'' ,'' ,'-' ,'-' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'' ,'-' ,'' ,'-' ,'-' ,'' ,'' ,'' ,'' ,'' ,'-' ,'-' ,'-','-');
$newtitle = str_replace($code_entities_match, $code_entities_replace, $newurl);
$urltitle = strtolower($newtitle);

Unfortunately, the results are:
new-york-deadline-may-14th-2010-urgent
new-hampshire-deadline-may-19th-2010
new-jersey-

Herkes yardımcı olabilir?

2 Cevap

: Sen olarak preg_replace kullanabilirsiniz

$str = 'New York deadline May 14th, 2010 (urgent)';

$to = array('/deadline.*/','/^\s+|\s+$/','/\s+/');
$from = array('','','-');
$str = strtolower(preg_replace($to,$from,$str));

echo $str; // prints new-york

Burada olmayan bir regex yolu

$str = 'New York deadline May 14th, 2010 (urgent)';
$title = str_replace( ' ', '-', current( explode( ' deadline', $str ) ) );