这是我的问题
在单个 PHP 文件中,演示将 "123 Tree Street, Connecticut"
转换为 "123_tree_street_connecticut"
的正则表达式。
我已经成功用 _
替换了空格和逗号,但是无法在 php 中使用正则表达式更改字符大小写。
我所做的是
<?php
echo preg_replace('/(,\s|\s)/', '_', '123 Tree Street, Connecticut');
?>
它用 _
替换空格和逗号,但不能改变它的大小写。
任何人都可以指导我如何仅使用 php 和正则表达式完成它。
谢谢。
最佳答案
由于正则表达式替换将使用 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);
?>
关于php - 在php中将字符串大写转换为小写的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6383572/