简体   繁体   中英

Replace repeating characters with only one character in php

I want to check if a string contains more than or equals 3 times a letter/number and replace it with only one letter/number. For example:

IIIII havvvvve a bigggg tesssssttttt tomorrow soooo iiii 2222551111 haveeee to do this rightttttt

To became like this

I have a big test tomorrow so i 2551 have to do this right. 

How can this be done with preg_replace ?

Regex:

([A-Za-z0-9])\1\1+

This would match more than or equals 3 times a letter/number and captures the first letter or Number. Finally the whole string was replaced with the character in the group index 1.

Replacement string:

\1

DEMO

<?php
$text = 'IIIII havvvvve a bigggg tesssssttttt tomorrow soooo iiii 2222551111 haveeee to do this rightttttt';
$pattern = '~([A-Za-z0-9])\1\1+~';
echo preg_replace($pattern,'\1',$text);
?>

Output:

I have a big test tomorrow so i 2551 have to do this right
([A-Za-z0-9])(\1{2,})?

Try this.Replace with $1.

See demo..

http://regex101.com/r/sA7pZ0/27

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM