2011-10-15 48 views
0

我已經得到了那句「rising_car_insurance_costs.php」我想使用的preg_replace刪除.php爲:的Preg更換PHP

$news = preg_replace('/^[a-zA-Z0-9_\.\-]+[.php]/', '$1 + ''', end($parts)); 

我也想更換_與空間,我可以做,但我也想把第一個字母寫成大寫字母(如果它是一封信) - 這甚至可能嗎?

感謝 山姆

回答

2

無需正則表達式

我想使用的preg_replace刪除.php爲:

$news = basename(end($parts), '.php'); 

我猜$parts意味着,你分裂使用explode()/的路徑。當你使用basename()時,你也可以避免這一步。

我也想用一個空間

$news = str_replace('_', ' ', $news); 

我也想打的第一個字母一個大寫字母

$news = ucfirst($news); 
+0

併爲_去除使用str_replace函數。 – janoliver

-1

它看起來像更換_你想使用preg_replace_callback並做其他的東西:

$news = preg_replace_callback('/^([a-zA-Z0-9_\.\-]+)[.php]$/', 'rewrite', 

function rewrite($match) { 
    $str = $match[1]; 
    ... strtr("_", " "); 
    ... ucwords(); 
    return $str; 
} 
+0

我認爲他們是一種使用preg_replace與$匹配字符串的各個部分的方法? – Technotron

+0

當然有。但只用一個正則表達式來封裝一封信是不可行的。你似乎對'/ e'語法有一些困惑,所以_callback是可取的。 – mario

0
$news = ucfirst(trim(preg_replace('/(?:_|\.php$)/i', ' ', end($parts))); 

爲了解釋:

  • ucfirst()轉換爲大寫的字符串的第一個字符
  • trim()修剪從字符串
  • preg_replace()的開始和結束的空間替代以下的正則表達式(不區分大小寫,/i)用空格
    • (?:...)是一個非捕獲表達,對於使用後|
    • _指任何「_」字符
    • |手段「或」
    • \.php$指序列「.PHP」在的結尾有用串
+0

感謝您的幫助 – Technotron

+0

這是什麼意思? – Technotron

+0

@ user990580,它是[subpattern](http://www.php.net/manual/en/regexp.reference.subpatterns.php),但沒有捕獲。如果你不添加'?:',那麼匹配將被存儲在'\ 1'中。這樣,它只是意味着它不會被存儲(更多是因爲性能方面的原因)。 – rid

0

更容易不的preg_replace:

$without_php = str_replace('.php', '', end($parts)) 
$without_underscores = str_replace('_', ' ', $without_php); 
$uppercased = ucfirst($without_underscored); 

All in one的:

$result = ucfirst(str_replace(array('.php', '_'), array('', ' '), end($parts)));