I am trying to figure how to use this on case sensitive words where the case is kept the same just the latters changed.

For example
$line = preg_replace("/(h)ello/i","\1owdy", $line);
this will change these 3
hello - howdy
Hello - Howdy
HELLO - Howdy

How can I make it so the HELLO turns to HOWDY

and also what if the replacing letter is not the same
How would I do for example

$line = preg_replace("/(h)ello/i","G'day", $line);

Confused... 🙂

Thanks,
Jeff

    Brett, whle that answered some questions, it mostly deals with the pattern itself. My problem is trying to figure out what to replace it with.

    In the same
    $line = preg_replace("/(h)ello/i","\1owdy", $line);

    That leaves the first character alone the "H" but what if I want to replace the first character with anohter and match the case?

    say replace h with g and H with G

    \1 seems to just skip right? How would I determeine to replace upper or lower with a new character?

    Thanks,
    Jeff

      That's out of my league. Sorry.

      ~Brett

        I don't think there's an easy way (someone please correct me if I'm wrong), but you could try

        function matchCase($matches)
        {
            $replacement = 'howdie';
            if (ctype_upper($matches[0])){
                return strtoupper($replacement);    
        } else if (ctype_upper(substr($matches[0],0,1))){ return ucwords($replacement); } else { return strtolower($replacement); } } $input = "Hello hello HELLO HeLLo hEllO"; $output = preg_replace_callback("/hello/i", "matchCase", $input); echo $output;

        As you can see, it only deals with all uppercase, all lowercase or first letter capitalized, ignoring single uppercase letters later within the word, so: feel free to modify & improve.

          I'm not sure if it fully fits your requirements, but you can use a character class which will match either lower case 'h' or capital 'H':

          "/([hH])ello/\1owdy/i"

          thus, "\1" is exactly (case sensitive) the character matched in the original string.

            Write a Reply...