preg_replace regular expression not working

I'm trying to remove a word, the word "the" to be precise from a title so the links will work correctly.

I thought it would just be this:

$title = 'Brother! The house is on fire!';
$sometitle = preg_replace('/^the$/','',$title);

or

$title = 'Brother! The house is on fire!';
$sometitle = preg_replace("/^the$/","",$title);

But neither appear to do anything. I only want the word "the" removed when it is by itself. I tried str_replace as well, but it removed all instances of the word "the".
I'm not super experienced with regular expressions and most of what I found on google showed it like one of the two above. Any ideas?

Re: preg_replace regular expression not working

Posted 04 April 2012 - 04:13 PM

The ^ and $ chars represent the beginning and end of a line. So if you do /^the$/, you are saying: "A line containing only the word 'the'."

What e_i_pi suggested uses the \b char instead, which represents the start or end of a word. That changes the expression to: "The distinct word 'the', anywhere in the line." - Also, the i after the expression makes it case-insensitive. They are case-sensitive by default.

Re: preg_replace regular expression not working

Have you tried using /\bthe\b/i as your match pattern? That should grab the word "the". There's a useful resource here for PHP regex.

That worked! Did exactly what I wanted. I read the first little bit of that link before posting here, guess I misunderstood when he said ^ means any string that starts with something or $ means any string that ends with something. I assumed it meant any string within what you're searching through(Each individual word). XD

Atli, on 04 April 2012 - 04:13 PM, said:

The ^ and $ chars represent the beginning and end of a line. So if you do /^the$/, you are saying: "A line containing only the word 'the'."

What e_i_pi suggested uses the \b char instead, which represents the start or end of a word. That changes the expression to: "The distinct word 'the', anywhere in the line." - Also, the i after the expression makes it case-insensitive. They are case-sensitive by default.

Thank you for explaining that. Makes more sense now.

sBorg, on 05 April 2012 - 01:59 AM, said:

Why do you even need to use preg_replace if you just intend replace the word "the" with ""?

A simple str_replace (or str_ireplace for case-insensitive search and replace) would do the job!

I tried that, but it would replace 'the' everywhere in the string, even if it was in another word. So, "brother" would become bror, "other" would become or, etc.