PHP question

General March 8th, 2004

I’m playing with some new functionality for the blog tonight, and have a PHP question about preg_replace(). Here’s an example:

$string = "Some PHP functions are complex.";

# \b is a word boundry, and i means ignore case
$translate["/\bsome\b/i"] = “most”;

$new_string = preg_replace(array_keys($translate), array_values($translate), $string);

echo $new_string;

Which would output (note the case) “most PHP functions are complex.”

What I want the match to do is match on any case of the word but keep the original capitalization (so that if the word starts a sentence, its replacement is capitalized, but if it’s in the middle of the sentence it’s not.) I think I should use preg_replace_callback() but I don’t know if it sends the original non-modified to the function or not.

*Dave codes some stuff*

By the time I asked the question, I knew how to test it, and did so. I’ll answer my own question.

preg_replace_callback() does pass the original value with its original capitalization, and write a function to look at that and make sure it’s replacement capitalization matches. (This means, and it should have been obvious earlier, that putting the /i modifier on the scan just matches what it accepts as a match, it doesn’t alter the source. My problem was putting all of my replacement text (the values in the $translate array) as lowercase. The function solution should fix that. A regexp to check for case, and the ucfirst() function should fix that right up.

Sweet. But that’s enough coding for tonight. More about my weekend tomorrow.