简体   繁体   中英

How to convert the character to uppercase, except the string in any () in php?

I have a string like this:

abc(abc)(ABC)(abc)abc abc(abc)(ABC)(abc)abc

And I want to convert this into

ABC(abc)(ABC)(abc)ABC ABC(abc)(ABC)(abc)ABC

And there may be some character like this

$str= a+b*(a+b)<sup>2</sup>+something.

You might be able to do it via REGEXP but that could have issues if there are compounded parenthesis... Something like this would work:

$open = 0;
$text = "abc(abc)(ABC)(abc)abc abc(abc)(ABC)(abc)abc";

for ($i = 0; $i < strlen($text); $i++) {
    switch ($text[$i]) {
    case '(':
    case '<':
        $open++;
        break;
    case ')':
    case '>':
        $open--;
        break;
    default:
        if ($open === 0) {
            $text[$i] = strtoupper($text[$i]);
        }
    }
}

This is assuming you don't want to make your html tags uppercase, and that there isn't a mismatch in opening/closing parenthesis or angle brackets.

If "$str=" could be part of the string, you could change the for loop to:

for ($i = strpos($text, '=') ?: 0; $i < strlen($text); $i++) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM