Home > Backend Development > PHP Tutorial > 驼峰 - php匹配字符串中大写字母的位置

驼峰 - php匹配字符串中大写字母的位置

WBOY
Release: 2016-06-06 20:41:25
Original
1340 people have browsed it

变量名用的是驼峰,数据库中字段中的是下划线,现在想把userId等变量批量转换成user_id,怎么样获取大写字母在字符串中的位置?

回复内容:

变量名用的是驼峰,数据库中字段中的是下划线,现在想把userId等变量批量转换成user_id,怎么样获取大写字母在字符串中的位置?

http://3v4l.org/kC52c

<code>echo preg_replace_callback("/[A-Z]/", function($ma){return "_".strtolower($ma[0]);}, "userId"); //user_id
</code>
Copy after login

谢谢 @公子 的回答,让我又发现了一个这么实用的网站。

公子的回答,会把 OpenZIP 变成 open_z_i_p

下面是我的代码:

http://3v4l.org/hIQUW

<code>echo strtolower(preg_replace('/((?</code>
Copy after login

可以试试 OpenZIP 变成了 open_zip

From:laravel4

<code>     /**
     * Convert a string to snake case.
     *
     * @param  string  $value
     * @param  string  $delimiter
     * @return string
     */
    function snake($value, $delimiter = '_')
    {
        $replace = '$1'.$delimiter.'$2';

        return ctype_lower($value) ? $value : strtolower(preg_replace('/(.)([A-Z])/', $replace, $value));
    }
</code>
Copy after login

echo preg_replace('/([A-Z])/', '_$1', 'AbcDefGhijk');貌似这样更简单一点

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template