REGEX: how to match exact word, not just an instance

let’s say I had this string($a) and I wanted to replace the ‘for’ in the string, how would i do it without replace all instances of the word?


$a="and before i was for...";
$b=str_replace('for'," ",$a);
echo $b;

this outputs:
and be e i was …
this isn’t what i want.
I just want the ‘for’ in the string replaced.
Anyone help please?

Use preg_replace and a word boundary check


$a="and before i was for...";
$b=preg_replace( '#\\bfor\\b#'," ",$a);
echo $b;

\b is the word boundary

that worked ! Thanks, regex is so confusing. are there any good tutorials? I actually tried what you have, but without the ‘#’. what do they do?

the # is a delimiter, it could be anything apart from alpha-numeric or backslash.

The delimiter starts and ends the regex pattern and tells the parser where to start and stop.

There are a few good tutorials online and I remember breaking down a regex and explaining it on here. Have a search of the php forum for regex - there are plenty to go for! If I find the thread I will post a link

cool. much appreciated.

Links:

http://www.javaregex.com/agame.html
http://us2.php.net/manual/en/ref.pcre.php

Have a look and play through that lot!