我想重命名以下声明:
<?php
$sentence = "I-am-a-GOOD-programmer-(but-only-in-PHP)";
$do = ucwords($sentence);
echo $do;
?>
上面的代码将输出为:
I-am-a-GOOD-programmer-(but-only-in-php)
如何获得输出:
I-Am-A-Good-Programmer-(But-Only-In-Php)
答案 0 :(得分:1)
$sentence = "I-am-a-good-programmer-(but-only-in-PHP)";
$sentence = preg_replace_callback('/(^|[-(])(\w+)/', function ($match) { return $match[1] . ucwords($match[2]); }, $sentence );
var_dump($sentence);
将导致:
string(40) "I-Am-A-Good-Programmer-(But-Only-In-PHP)"
^ | [ - (]表示开头或者a - 或(并且可以使用您需要的任何其他字符轻松扩展,或者您可以使用\ W,这意味着任何非单词字符。
\ w +表示单词字符(字母字符)。
答案 1 :(得分:0)
<?php
$msg = 'I-am-a-good-programmer-(but-only-in-PHP)';
$msg_replaced = preg_replace_callback('#([^\w]*)?(\w+)([^\w]*)?#', function($matched)
{
return $matched[1] . ucwords($matched[2]) . $matched[3];
}, $msg);
echo $msg_replaced;//I-Am-A-Good-Programmer-(But-Only-In-PHP)
?>
答案 2 :(得分:0)
找到解决问题的方法:
<?php
$sentence = "I-am-a-GOOD-programmer-(but-only-in-PHP)";
$sentence = str_replace("-"," ",$sentence);
$do = ucfirst($sentence);
echo $do;
?>
它按照我的要求提供输出:
I Am A Good Programmer (But Only In Php)