Maison >développement back-end >tutoriel php >请问PHP用正则表达式字符串,只想保留第一个该如何做?
PHP
比如说这个字符串有很多个asd,有连续几个的,也有只是一个的,
但是我想只保留第一个asd,后面的asd全部删掉,该怎么做?
(在不影响其他字符的基础上)
ssssssssgsdfasdasdasdasdjlkjhkjhalkasdasdjsdkajshdasdaklsjdasdhkjashgdaklsh
想要的结果:
ssssssssgsdfasdjlkjhkjhalkjsdkajshdaklsjdhkjashgdaklsh
求高手给点提示
$s = 'ssssssssgsdfasdasdasdasdjlkjhkjhalkasdasdjsdkajshdasdaklsjdasdhkjashgdaklsh';$t = 'ssssssssgsdfasdjlkjhkjhalkjsdkajshdaklsjdhkjashgdaklsh';$s = preg_replace_callback('/asd/', function($r) { static $n = 0; return ! $n++ ? $r[0] : ''; }, $s);var_dump($s == $t);bool(true)
一天没时间,非常非常感谢版主,对,就是这个效果,原来还有preg_replace_callback这么好用的东西,preg_replace是不是没这个功能呀?版主