[英]Regular Expression to convert String upper case to lower case in php
Here is my problem 这是我的问题
In a single PHP file, demonstrate a regular expression to convert "123 Tree Street, Connecticut"
into "123_tree_street_connecticut"
. 在单个PHP文件中,演示一个正则表达式,将
"123 Tree Street, Connecticut"
转换为"123_tree_street_connecticut"
。
I have successfully replace spaces and comma with _
, but unable to change character case using Regular expression in php. 我已成功用
_
替换空格和逗号,但无法使用php中的正则表达式更改字符大小写。
what i have did is 我所做的是
<?php
echo preg_replace('/(,\s|\s)/', '_', '123 Tree Street, Connecticut');
?>
It replaces spaces and commas with _
but not able to change it's case. 它用
_
替换空格和逗号但不能改变它的情况。
Can any one guide me to how it is done Using php and regular expression only. 任何人都可以指导我如何完成它只使用PHP和正则表达式。
Thanks. 谢谢。
Since the regex replacement will use the strtolower()
function, I see no reason to not just do it all with simple string functions: 由于正则表达式替换将使用
strtolower()
函数,我认为没有理由不使用简单的字符串函数来完成所有操作 :
<?php
$str = '123 Tree Street, Connecticut';
$str = strtolower(str_replace(array(', ', ' '), '_', $str));
print_r($str);
?>
If strtolower()
is not "allowed", you could perform a shift based on the character table distance between upper- and lowercase letters. 如果
strtolower()
不是“允许”,则可以根据大写和小写字母之间的字符表距离执行移位。 It's not pretty but it seems to work (in this specific case): 它不漂亮,但它似乎工作 (在这种特定情况下):
<?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功能。
Input : 输入:
<?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"));
?>
Output : 输出:
123_tree_street_connecticut
123_tree_street_connecticut
Hope this helps you. 希望这对你有所帮助。 Thanks!!
谢谢!!
I am not sure there is any built-in regex solution for to change the case. 我不确定是否有任何内置的正则表达式解决方案来更改案例。 But I think you can do it by hands by writing a new regex for every character.
但我认为你可以通过为每个角色编写一个新的正则表达式来完成。
Converting to upper case example: 转换为大写示例:
$new_string = preg_replace(
array('a', 'b', 'c', 'd', ....),
array('A', 'B', 'C', 'D', ....),
$string
);
I think you got the point. 我认为你明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.