开发者

Regular Expression to convert String upper case to lower case in php

开发者 https://www.devze.com 2023-03-13 10:55 出处:网络
Here is my problem In a single PHP file, demonstrate a regular expression to convert \"123 Tree Street, Connecticut\" into \"123_tree_street_connecticut\".

Here is my problem

In a single PHP file, demonstrate a regular expression to convert "123 Tree Street, Connecticut" into "123_tree_street_connecticut".

I have successfully replace spaces and comma with _, but unable to cha开发者_JS百科nge character case using Regular expression in 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.

Thanks.


Since the regex replacement will use the strtolower() function, I see no reason to not just do it all with simple string functions:

<?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. 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);

?>


Use strtolower function instead.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消