views:

28

answers:

1

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 "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 RTFM 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?

A: 
$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

Amber