开发者

How to write a regular expression for "everything between X and Y" for use with preg_replace

I want to take a variable called $encoded_str and and remove cd1, CD1 and anything between the first 'l' and the last blank space. So for example开发者_StackOverflow中文版 "lp6 id4 STRINGcd1" would return "STRING".

I'm using PHP 4 for now so I can't use str_ireplace, I have this:

$encoded_str=str_replace('CD1','',$encoded_str);
$encoded_str=str_replace('cd1','',$encoded_str);
$encoded_str=preg_replace('X','',$encoded_str);

I've RTM for preg_replace but am a bit confused. What should I replace the X with and can you suggest a decent introductory primer for writing regular expressions?


$encoded_str=preg_replace('/l.*(?<=\s)/','',$encoded_str);

The above regex will match anything from the first l in the string to the last whitespace. It uses a positive lookbehind to match the position of a whitespace character as the ending point for the .* that's consuming the first part of the string. Since .* is greedy, the lookbehind will match the last whitespace character it can.

As far as a reference, these pages are great:

http://www.regular-expressions.info/tutorial.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜