将双引号或单引号之间的所有字符转换为ALL CAPS

时间:2015-02-26 11:44:28

标签: php regex

我有一个字符串:

$str = "Marry had \"little lamb\".SHe was very cute";

我希望匹配""''之间的字符串,然后将其设为大写字母,然后在PHP网站上显示。

像这样:

Marry had "LITTLE LAMB". SHe was very cute

任何人都可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

您可以通过preg_replace_callback函数实现此目的。

$str = "Marry had \"little lamb\".SHe was very cute";
echo preg_replace_callback('~"[^"]*"|\'[^\']*\'~', function ($m)
        { 
            return strtoupper($m[0]);
        }, $str);

输出:

Marry had "LITTLE LAMB".SHe was very cute

注意:我认为您的输入不会包含任何转义引号。

答案 1 :(得分:0)

$str = "Marry had \"little lamb\".SHe was very cute";

    $x = explode('"',$str);
foreach($x as $val)
{
  $y[] = ucfirst(trim($val));

}
$str = implode('.',$y);
echo $str;
嗯...我不明白你的问题我想我的意思是你的代码只是切换了。到"在爆炸中你可以解释一下,如果那不是你的目标,谢谢你

答案 2 :(得分:0)

基本上,您可以像这样描述双引号之间的内容:

"[^"]*"

但请注意,如果内部有双重引号,则会失败。所以处理它们的方法是两个写:

"(?s:[^"\\]+|\\.)*+"

或在php单引号中:

$pattern = '~"(?s:[^"\\\]+|\\\.)*+"~';

但为了提高性能,模式可以展开,如下所示:

$pattern = '~"[^"\\\]*+(?:\\\.[^"\\\]*)*+"~';

要使内容为大写,您需要使用允许使用函数替换的preg_replace_callback

$result = preg_replace_callback($pattern, function ($m) { return strtoupper($m[0]); }, $str);