2

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 change 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.

3
  • 3
    do you have to do it with regular expressions? Jun 17, 2011 at 9:05
  • 1
    This is not a good problem to be solved with regular expressions, use strtolower instead.
    – Jens
    Jun 17, 2011 at 9:05
  • 1
    Sounds like homework. If it is, it would be polite to say so and show what you've done so far. Jun 17, 2011 at 9:07

4 Answers 4

5

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

?>
3

Use strtolower function instead.

1

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!!

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.