[英]Regular Expression to convert String upper case to lower case in php
這是我的問題
在單個PHP文件中,演示一個正則表達式,將"123 Tree Street, Connecticut"
轉換為"123_tree_street_connecticut"
。
我已成功用_
替換空格和逗號,但無法使用php中的正則表達式更改字符大小寫。
我所做的是
<?php
echo preg_replace('/(,\s|\s)/', '_', '123 Tree Street, Connecticut');
?>
它用_
替換空格和逗號但不能改變它的情況。
任何人都可以指導我如何完成它只使用PHP和正則表達式。
謝謝。
由於正則表達式替換將使用strtolower()
函數,我認為沒有理由不使用簡單的字符串函數來完成所有操作 :
<?php
$str = '123 Tree Street, Connecticut';
$str = strtolower(str_replace(array(', ', ' '), '_', $str));
print_r($str);
?>
如果strtolower()
不是“允許”,則可以根據大寫和小寫字母之間的字符表距離執行移位。 它不漂亮,但它似乎工作 (在這種特定情況下):
<?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);
?>
請改用strtolower功能。
輸入:
<?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
希望這對你有所幫助。 謝謝!!
我不確定是否有任何內置的正則表達式解決方案來更改案例。 但我認為你可以通過為每個角色編寫一個新的正則表達式來完成。
轉換為大寫示例:
$new_string = preg_replace(
array('a', 'b', 'c', 'd', ....),
array('A', 'B', 'C', 'D', ....),
$string
);
我認為你明白了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.