Home >Backend Development >PHP Tutorial >正则太菜【继续】

正则太菜【继续】

WBOY
WBOYOriginal
2016-06-13 10:25:14874browse

正则太菜【继续求助】
aaa.bbb.ccc.ddd $aaa.bbb.ccc.ddd... aaa.bbb.ccc.ddd
用正则如何替换成
aaa.bbb.ccc.ddd $a.b.c.d... aaa.bbb.ccc.ddd

刚两次提问都没提问道点子上

------解决方案--------------------
先上个试试。。

PHP code
$str = 'aaa.bbb.ccc.ddd $aaa.bbb.ccc.ddd... aaa.bbb.ccc.ddd';echo preg_replace_callback('/\$([a-z]+)((?:.[a-z]+)+)/i', 'test', $str);function test($m){    $arr = explode('.',trim($m[0], '$'));    $join = array();    foreach($arr as $a) {        $join[] = $a[0];    }    return '$' . implode($join, '.');}/**输出:aaa.bbb.ccc.ddd $a.b.c.d... aaa.bbb.ccc.ddd*/<br><font color="#e78608">------解决方案--------------------</font><br>
PHP code
$s = 'aaa.bbb.ccc.ddd $aaa.bbb.ccc.ddd... aaa.bbb.ccc.ddd';echo preg_replace_callback('/\$[^\s]+/', 'back', $s);function back($r) {  return preg_replace('/(\w)+/', '$1', $r[0]);}<div class="clear">
                 
              
              
        
            </div>
Statement:
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