请教一个正则替换问题

WBOY
Release: 2016-06-23 13:59:05
Original
799 people have browsed it

有这样的字符串 比如:

get_post_title

find_my_article


这样的字符串,如何用正则替换成:GetPostTitle,FindMyArticle ?

用explode,array_map(ucword),这样的法子用过了。现在想用正则实现,奈何功力不够啊


这个正则该如何写法?


回复讨论(解决方案)

$s = 'get_post_title';echo preg_replace('/(^|_)(\w)/e', 'strtoupper("$2")', $s);
Copy after login
Copy after login

$s = 'get_post_title';echo preg_replace('/(^|_)(\w)/e', 'strtoupper("$2")', $s);
Copy after login
Copy after login


谢谢斑竹。能说说这个正则式的分析思路么?

如果是这样的字符串 :a,b,c,d 变成 'a','b','c','d' 呢?正则又如何写法?

这样写比较好,e 属性已经列在废止之列了

$s = 'a,b,c,d';echo preg_replace_callback('/(?:^|,)([a-z])/', function($r) { return "'$r[1]'";}, $s);
Copy after login
Copy after login

谢谢啦。不过我在用Javascript实现这个的时候,貌似有些不对。请点解下

"get_post_title".replace(/(^|_)(\w)/g,function($2){return $2.toUpperCase();})//返回这样的结果:Get_Post_Title
Copy after login


不知道为啥

这样写比较好,e 属性已经列在废止之列了

$s = 'a,b,c,d';echo preg_replace_callback('/(?:^|,)([a-z])/', function($r) { return "'$r[1]'";}, $s);
Copy after login
Copy after login


运行的结果不太对。
我自己这样写的:
$s = 'a,b,c,d';echo preg_replace_callback('/(\w)/', function($r) { return "'$r[1]'";}, $s);
Copy after login

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