Home > Backend Development > PHP Tutorial > 请问PHP用正则表达式字符串,只想保留第一个该如何做?

请问PHP用正则表达式字符串,只想保留第一个该如何做?

WBOY
Release: 2016-06-23 14:20:14
Original
836 people have browsed it

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); 
Copy after login
bool(true) 

一天没时间,非常非常感谢版主,对,就是这个效果,原来还有preg_replace_callback这么好用的东西,preg_replace是不是没这个功能呀?版主

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template