请教PHP用正则表达式字符串,只想保留第一个该怎么做
时间:2021-07-01 10:21:17
帮助过:38人阅读
请问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)