I'm using preg_replace in PHP to find and replace specific words in a string, like this:
$subject = "Apple apple";
print preg_replace('/apple/i', 'pear', $subject);
Which gives the result 'pear pear'.
What I'd like to be able to do is to match a word in a case insensitive way, but respect it's case when it is replaced - giving the result 'Pear pear'.
The following works, but seems a little long winded to me:
$pattern = array('/Apple/', '/apple/');
$replacement = array('Pear', 'pear');
$subject = "Apple apple";
print preg_replace($pattern, $replacement, $subject);
Is there a better way to do this?
Update: Further to an excellent query raised below, for the purposes of this task I only want to respect 'title case' - so whether or not the first letter of a word is a capital.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…