Ben G
Ben G

Reputation: 26761

Remove letters and spaces which immediately follow the first two letters in a string

I'm trying to replace all the letters and spaces after the first two, using PHP's preg_replace(). Here is my failed attempt at doing so:

echo preg_replace('/^[a-zA-Z]{2}([a-zA-Z ])*.*$/i','','FALL 2012');
//expected output is "FA2012", but it outputs nothing

I'm just trying to replace the part in parentheses ([a-zA-Z ]) .. I'm guessing I'm not doing it right to just replace that part.

Upvotes: 2

Views: 111

Answers (4)

Samir Talwar
Samir Talwar

Reputation: 14330

You're asking it to replace the entire string. Use a lookbehind to match the first two characters instead.

echo preg_replace('/(?<=^[a-z]{2})[a-z ]*/i','','FALL 2012');

By the way, the i modifier means it's case insensitive, so you don't need to match both uppercase and lowercase characters.

Upvotes: 2

jaytea
jaytea

Reputation: 1949

In this case you can get away with a (?<=lookbehind); however, in certain other cases you may find the \K escape to be more suitable. What it does is reset the start offset value passed by the application to the current position in the subject, effectively dumping the portion of the string that was consumed thus far in the current match. For example:

preg_replace('^[a-z]{2}\K[a-z ]*/i', '', 'FALL 2012')

Now only the substring matched by [a-z ]* is substituted.

Upvotes: 1

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

you are saying to replace the entire match with blank (''). You want to put the parenthesis around the parts you want to keep and then replace with $1$2 which is equal to what is in the first ($1) and second ($2) set of parenthesis.

preg_replace("/^([a-z]{2})[a-z\s]*(.*)$/i", '$1$2', $string);

Upvotes: 0

agent-j
agent-j

Reputation: 27913

The /i at the end makes it case-insensitive. The (?<=regex) means look immediately before the current position for the beginning of the line followed by 2 letters.

echo preg_replace('/(?<=^[a-z]{2})[a-z ]*/i','','FALL 2012');

Upvotes: 0

Related Questions