我用php中的'firstNameUser'取代first_name_user
。我如何在下劃線後用大寫字母php正則表達式
我想這
$key1 = preg_replace('/_([a-z]?)/', '\U\1', $key);
和它不工作
我用php中的'firstNameUser'取代first_name_user
。我如何在下劃線後用大寫字母php正則表達式
我想這
$key1 = preg_replace('/_([a-z]?)/', '\U\1', $key);
和它不工作
$key1 = preg_replace('/_([a-z]?)/e', 'strtoupper("$1")', $key);
但這種使用具有some issues security implications是deprecated as of PHP 5.5.0反正在e
modifier。
Use of this modifier is discouraged, as it can easily introduce security vulnerabilites
更好地利用:
$key1 = preg_replace_callback('/_([a-z]?)/', function($match) {
return strtoupper($match[1]);
}, $key);
更多的例子/代碼和信息,請參見this question和this question。
候補@roblll答案,如果你不希望使用正則表達式,你可以使用:
$str = "some_underscored_text";
$new_str = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
echo $new_str; // Outputs: someUnderscoredText
會導致問題,就像'SOME_VALUE foo_bar這樣baz_foo'一個字符串,它應* *'成爲someValue中fooBar bazFoo',但*會變成'someValueFooBarBazFoo'。用「佔位符」替換字符,然後再返回幾乎總是會導致比解決問題更多的問題。如果你真的想避免使用正則表達式,使用標記器。 – RobIII
@RobIII我明白你的意思了,我以爲它應該是one_underscored_string_per_call而不是包含下劃線短語的句子:) –
假設是所有f * ckups的母親;-)但我同意;當這種情況發生時(或者是),應該可以正常工作,OP在他/她的問題中不清楚這一點。只是這種方法(通常使用「佔位符」)*通常不是一個好主意。 – RobIII