


An example of how to convert camel case strings into underline style strings in PHP
这篇文章主要介绍了PHP实现驼峰样式字符串(首字母大写)转换成下划线样式字符串的方法,涉及php正则替换相关操作技巧,需要的朋友可以参考下
本文实例讲述了PHP实现驼峰样式字符串(首字母大写)转换成下划线样式字符串的方法。分享给大家供大家参考,具体如下:
1、如何在php中把驼峰样式的字符串转换成下划线样式的字符串。例:输入是FooBar的话,输出则是foo_bar
以下是用正则的方式去完成,既然用到正则,方法肯定就不只一种,我们看下下面的方式
echo strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', 'fooBar')); //output:foo_bar echo "<br>"; echo strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', 'foo')); //output:foo echo "<br>"; echo strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', 'fooBarB')); //output:foo_bar_b echo "<br>";
下面我们来解释下,上面正则的意思。具体正则的基本知识,这里篇幅有限就不具体介绍了,文章末尾会附带几篇总结的比较好的正则表达式的文章。
上面的正则里面主要用到了正则表达式中的环视边界匹配的语法。具体定义如下(摘抄):
环视的字面意思就是左右看看,需要左右符合一些条件,本质上,它也是匹配边界,对边界有一些要求,这个要求是针对左边或右边的字符串的,根据要求不同,分为四种环视:
肯定顺序环视,语法是(?=...),要求右边的字符串匹配指定的表达式,比如表达式abc(?=def),(?=def)在字符c右面,即匹配c右面的边界,对这个边界的要求是,它的右边有def,比如abcdef,如果没有,比如abcd,则不匹配;
否定顺序环视,语法是(?!...),要求右边的字符串不能匹配指定的表达式,比如表达式s(?!ing),匹配一般的s,但不匹配后面有ing的s;
肯定逆序环视,语法是(?<=...),要求左边的字符串匹配指定的表达式,比如表达式(?<=\s)abc,(?<=\s)在字符a左边,即匹配a左边的边界,对这个边界的要求是,它的左边必须是空白字符;
否定逆序环视,语法是(?
可以看出,环视也使用括号(),不过,它不是分组,不占用分组编号。
继续回到我们上面的正则表达式,第一个小括号(?<=[a-z]),这是肯定逆序环视的语法,要求匹配的字符串的左边必须有小写的字母。第二个小括号则是一个分组,匹配大写的字母,注意正则中的分组编号是从1开始的,这和我们传统编程下标一般是从0开始不同。而第一个小括号本身就是语法,其不占用分组编号,所以后面的$1,则是匹配的第二个小括号中的内容,并将其前面添加一个_符号,最后再整体将整个字符串转换成小写。
既然我们已经能把驼峰法转为下划线的样式了,如果反过来又该怎办呢?
2、如何在php中把下划线样式的字符串转换成驼峰样式的字符串。例:输入是foo_bar的话,输出则是FooBar
$str = preg_replace_callback('/_+([a-z])/',function($matches){ print_r($matches); //Array ( [0] => _b [1] => b ) return strtoupper($matches[1]); },'foo_bar'); echo $str; //fooBar echo "<br>"; $str = preg_replace_callback('/_+([a-z])/',function($matches){ return strtoupper($matches[1]); },'foo'); echo $str; //foo echo "<br>"; $str = preg_replace_callback('/_+([a-z])/',function($matches){ return strtoupper($matches[1]); },'foo_bar_b'); echo $str; //fooBarB echo "<br>";
这里我们用到了preg_replace_callback
函数,该函数执行一个正则表达式搜索并且使用一个回调进行替换。换言之,就是第一个参数是正则表达式,第二个参数是一个匹配到结果的回调函数,第三个参数是需要匹配的字符串。注意,回调函数具体什么时候调用,是每次匹配到结果则调用,调用次数不只为一次,匹配不到则不调用。并且该回调函数的参数是匹配的结果,是完整的匹配,matches[0]
是完整的匹配,matches[1]
是第一个捕获子组的匹配,以此类推。且回调函数需要把更改的结果return出去,不然则忽略捕获的字符串
正则表达式比较简单,这里就不具体分析了。
The above is the detailed content of An example of how to convert camel case strings into underline style strings in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
