You are here: Re: RegExp for a substring « PHP Programming Language « IT news, forums, messages
Re: RegExp for a substring

Posted by Rik on 06/14/06 11:55

Csaba Gabor wrote:
> Suppose I want to check that a string, $str, starts with at least the
> first 3 letters of a given word, say "delete". Can I do that
> compactly with a regular expression? The following are not my idea
> of compact:
>
> preg_match("/^del(|e|et|ete)\\b/i", $str)
> Quadratic in the length of the given word
>
>
> preg_match("/^del(e(t(e)?)?)?\\b/i", $str)
> Really now. But at least it's linear
>

Euhm, why at LEAST 3?
You don't seem to be using 'more' matches.
Or is this just a quick example?

Normally, I wouldn't use regexes for this. The way you made them is about as
compact as they get for this particular purpose.

if(substr($str,0,3) = substr($needle,0,3){
//code...
}

If you're trying to do what I think you want, maybe this is the code for
you:
$needle = 'delete';
preg_match("/^[a-z]+\b/i", $str,$match);
if(strlen($match[0])>=3 && $match[0]==substr($needle,0,strlen($match[0]))){
//code if it matches
}

By no means shorter, but a lot more versatile.

Grtz,
--
Rik Wasmus

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация