Home > Net >  PHP Regex double instances of any character
PHP Regex double instances of any character

Time:02-18

Hi guys can someone help me with this

$input_lines= array("asdf","fdas", "asds", "d fm", "dfaa", "aaaa", "aabb", "aaabb");
preg_grep('/a{2}/', explode("\n", $input_lines));

Now this returns every string that has atleast 2 a BUT what I want is for it to return every string that has more than 2 character, whatever that character is whether a, b or s This is the output I want to achieve

asds 
dfaa 
aabb 
aaabb

CodePudding user response:

@Emmanuel, in this solution have a two key function unpack which help we can get the ASCII of each character from give string(that return as array) and array_unique using this we can convert to unique array and then check with it's original array count if it's less than original array than there is repeat character in it.

<?php
$input_lines= array("asdf","fdas", "asds", "d fm", "dfaa", "aaaa", "aabb", "aaabb");
    
    for($i=0;$i<count($input_lines);$i  )
    {
        
        $ChrFilter= unpack("C*",$input_lines[$i]);
        if(count(array_unique($ChrFilter))<count($ChrFilter))
        {
        echo $input_lines[$i];
        echo '<br>';
        }
        
    }
?>

Out Put:  
asds 
dfaa 
aaaa 
aabb 
aaabb

CodePudding user response:

You can use

$input_lines= array("asdf","fdas", "asds", "d fm", "dfaa", "aaaa", "aabb", "aaabb");
print_r(preg_grep('/(\p{L}).*\1/', $input_lines));

Note that '/(\p{L}).*\1/' regex matches any letter (capturing it into Group 1 with (\p{L})) and then matches any zero or more chars other than line break chars as many as possible (with .*) and then matches the same char as captured in Group 1. See the regex demo.

Output:

Array
(
    [2] => asds
    [4] => dfaa
    [5] => aaaa
    [6] => aabb
    [7] => aaabb
)

See the PHP demo.

  • Related