使用函数preg_replace获取下划线后的第一个字符(PHP)
我想获得带有下划线的字符串的所有前字符 例如:使用函数preg_replace获取下划线后的第一个字符(PHP),php,regex,preg-replace,Php,Regex,Preg Replace,我想获得带有下划线的字符串的所有前字符 例如: Input: hello_this_is_test Output: HTIT 是否可以通过regex和replace函数执行此操作 这就是我想要实现的目标: <?php $string = 'hello_this_is_test'; $pattern = '...'; $replacement = ''; echo strtoupper(preg_replace($pattern, $replacement, $string)); ?&g
Input: hello_this_is_test Output: HTIT
是否可以通过regex和replace函数执行此操作
这就是我想要实现的目标:
<?php
$string = 'hello_this_is_test';
$pattern = '...';
$replacement = '';
echo strtoupper(preg_replace($pattern, $replacement, $string));
?>
我缺少的是模式。任何人都可以帮我度过难关
谢谢 尝试使用以下模式使用
preg\u replace
:
(\w)[^_]*?(?:_|$)
然后替换为第一个捕获组
$string = 'hello_this_is_test';
$output = strtoupper(preg_replace("/(\w)[^_]*?(?:_|$)/", "$1", $string));
echo $output;
这张照片是:
HTIT
您希望删除从第二个字母到下一个下划线或字符串结尾(如果是)
\K
将按顺序匹配并释放第一个字母,然后保留要删除的以下字符
代码:()()
输出:
HTIT
HTIT
这里有一个不带正则表达式的替代方案,但是在只保留第一个字母后,使用以下命令将其替换为ing,然后返回: 演示:您还可以使用查找所有以单词开头的字符,对字符串开头或
\u
进行正向查找,然后使用所有匹配项的内爆
的大写字母:
$string = 'hello_this_is_test';
preg_match_all('/(?<=_|^)(.)/', $string, $matches);
echo strtoupper(implode('', $matches[1]));
请注意,如果允许下划线按顺序排列(例如,
),则这将匹配下划线本身,但通过使用[^.]
(或任何更具体的方法,如果需要的话)更改
,可以轻松解决此问题。@Jeto你说得对-但我只能按要求回答问题。用[a-zA-Z]
替换
肯定会确保字符以“word”开头,但没有其他示例数据和一些反例,我只是尽量保持简单。这是有意义的。这只是一个“以防万一”的通知:)@Jeto绝对-你的观点很好,我对评论投了更高的票,所以(希望)任何看到这个答案的人也会读到它。
$string = 'hello_this_is_test';
preg_match_all('/(?<=_|^)(.)/', $string, $matches);
echo strtoupper(implode('', $matches[1]));
HTIT