detect a string contained by another discontinuously

Posted by SpawnCxy on Stack Overflow See other posts from Stack Overflow or by SpawnCxy
Published on 2010-05-21T03:25:05Z Indexed on 2010/05/21 3:30 UTC
Read the original article Hit count: 149

Filed under:
|
|
|

Recently I'm working on bad content(such as advertise post) filter of a BBS.And I write a function to detect a string is in another string not continuously.Code as below:

$str = 'helloguys';
$substr1 = 'hlu';
$substr2 = 'elf';

function detect($a,$b) //function that detect a in b
{
    $c = '';
    for($i=0;$i<=strlen($a);$i++)
    {
        for($j=0;$j<=strlen($b);$j++)
        {
            if($a[$i] == $b[$j])
            {
               $b=substr($b,$j+1);
               $c .=$a[$i];
               break;
            }
        }
    }
    if($c == $a) return true;
    else return false;
}

var_dump(detect($substr1,$str)); //true
var_dump(detect($substr2,$str)); //false

Since the filter works before the users do their posts so I think the efficiency here is important.And I wonder if there's any better solution? Thanks!

© Stack Overflow or respective owner

Related posts about php

Related posts about string