请问PHP用正则表达式字符串,只想保留第一个该如何做?
PHP
比如说这个字符串有很多个asd,有连续几个的,也有只是一个的,
但是我想只保留第一个asd,后面的asd全部删掉,该怎么做?
(在不影响其他字符的基础上)
ssssssssgsdfasdasdasdasdjlkjhkjhalkasdasdjsdkajshdasdaklsjdasdhkjashgdaklsh
想要的结果:
ssssssssgsdfasdjlkjhkjhalkjsdkajshdaklsjdhkjashgdaklsh
求高手给点提示
[解决办法]
$s = 'ssssssssgsdfasdasdasdasdjlkjhkjhalkasdasdjsdkajshdasdaklsjdasdhkjashgdaklsh';bool(true)
$t = 'ssssssssgsdfasdjlkjhkjhalkjsdkajshdaklsjdhkjashgdaklsh';
$s = preg_replace_callback('/asd/', function($r) {
static $n = 0;
return ! $n++ ? $r[0] : '';
}, $s);
var_dump($s == $t);