这是我的问题
在单个PHP文件中,演示一个正则表达式,将"123 Tree Street, Connecticut"
转换为"123_tree_street_connecticut"
。
我已成功用_
替换空格和逗号,但无法使用php中的正则表达式更改字符大小写。
我所做的是
<?php
echo preg_replace('/(,\s|\s)/', '_', '123 Tree Street, Connecticut');
?>
它用_
替换空格和逗号,但无法改变它的情况。
任何人都可以指导我如何使用php和正则表达式。
感谢。
答案 0 :(得分: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 :(得分:3)
改为使用strtolower功能。
答案 2 :(得分: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
希望这会对你有所帮助。谢谢!
答案 3 :(得分:0)
我不确定是否有任何内置的正则表达式解决方案来更改案例。但我认为你可以通过为每个角色编写一个新的正则表达式来手工完成。
转换为大写示例:
$new_string = preg_replace(
array('a', 'b', 'c', 'd', ....),
array('A', 'B', 'C', 'D', ....),
$string
);
我认为你明白了。