2011-06-17 29 views
2

這裏是我的問題正則表達式字符串大寫轉換爲小寫在PHP

在一個單一的PHP文件,表明正則表達式"123 Tree Street, Connecticut"轉換成"123_tree_street_connecticut"

我已成功替換空格和逗號_,但無法在php中使用正則表達式更改字符大小寫。

我所做過的

<?php 
echo preg_replace('/(,\s|\s)/', '_', '123 Tree Street, Connecticut'); 
?> 

它代替空格和逗號與_,但不能改變它的情況。

任何人都可以指導我如何完成僅使用php和正則表達式。

謝謝。

+3

你必須用正則表達式來做它嗎? – 2011-06-17 09:05:05

+1

這不是正則表達式需要解決的問題,而是使用'strtolower'。 – Jens 2011-06-17 09:05:48

+1

聽起來像功課。如果是這樣,那麼說出來會很禮貌,並展示你迄今爲止所做的事情。 – 2011-06-17 09:07:23

回答

5

由於正則表達式替換將使用strtolower()功能,我看不出有什麼理由不只是do it all用簡單的字符串函數:

<?php 

$str = '123 Tree Street, Connecticut'; 
$str = strtolower(str_replace(array(', ', ' '), '_', $str)); 

print_r($str); 

?> 

如果strtolower()不「允許」,你可以進行基於轉變大寫字母和小寫字母之間的字符表距離。它不漂亮,但它seems to work(在這種特殊情況下):

<?php 

function shiftToLower($char) { 
    $ord = ord($char); 
    return $ord < 65 || $ord > 90 ? '_' : chr($ord + 32); // 65 = A, 90 = Z 
} 

$str = '123 Tree Street, Connecticut'; 
$str = preg_replace('/([, ]+|[A-Z])/e', "shiftToLower('\\1')", $str); 

print_r($str); 

?> 
1

輸入:

<?php 
// either use this // 
echo str_replace(',', '', str_replace(' ', '_', strtolower("123 Tree Street, Connecticut"))); 

echo "\n"; 

// or use this // 
echo str_replace(array(', ', ' '), '_', strtolower("123 Tree Street, Connecticut")); 
?> 

輸出:

123_tree_street_connecticut 
123_tree_street_connecticut 

希望這有助於你。謝謝!!

0

我不確定是否有任何內置的regex解決方案來更改案例。但我認爲你可以通過爲每個角色寫一個新的正則表達式來實現。

轉換爲大寫例如:

$new_string = preg_replace(
    array('a', 'b', 'c', 'd', ....), 
    array('A', 'B', 'C', 'D', ....), 
    $string 
); 

我想你了問題的實質。

相關問題