sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo reemplazar una cadena con otra cadena y mantener el caso en php y mysql?

Creé una función que reemplazará la palabra por ti y mantendrá los casos.

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

Nota:no se ha probado y es posible que necesite algunos ajustes