Jeg har oprettet en funktion, der erstatter ordet for dig og beholder sagerne.
function replaceWithCase($source, $replacement, $string) {
// Does the string contain the source word?
if (strpos($string, $source) === false) {
return false;
}
// If everything is uppercase, return the replacement fully uppercase
if (ctype_upper($source)) {
return str_replace($source, strtoupper($replacement));
}
// Set an array to work with
$characters = array();
// Split the source into characters
$sourceParts = explode('', $source);
// Loop throug the characters and set the case
foreach ($sourceParts as $k => $sp) {
if (ctype_upper($sp)) {
$characters[$k] = true;
} else {
$characters[$k] = false;
}
}
// Split the replacement into characters
$replacementParts = explode('', $replacement);
// Loop through characters and compare their case type
foreach ($replacementParts as $k => $rp) {
if (array_key_exists($k, $characters) && $characters[$k] === true) {
$newWord[] = strtoupper($rp);
} else {
$newWord[] = strtolower($rp);
}
}
return substr_replace($source, implode('', $newWord), $string);
}
// usage
echo replaceWithCase('AppLes', 'bananas', 'Comparing AppLes to pears');
Bemærk:det er utestet og skal muligvis justeres