php - 在php中将字符串大写转换为小写的正则表达式

标签 php regex

这是我的问题

在单个 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/

相关文章:

php - 管理循环中的多个 SQL 语句

javascript - reactStringReplace() 不一致的正则表达式匹配

php - 如何删除字符串中的所有非大写字符?

Php正则表达式匹配包含下划线或后跟数字的字符串

c - 如何让 Ultraedit 正则表达式搜索在 C/C++ 代码中工作

php - 插入查询不插入没有错误信息

php - 使用 php 的剩余时间脚本

php - 如何为第一个表中的每个结果查询第二个表?

php - 为什么我的 PHP session 消失了?为什么我无法恢复它们?

python - 正则表达式匹配任何保持序列顺序的字符串,即使它不完整