View Full Version : My str_replace() isn't working !

03-23-2009, 06:53 PM
I have the following code:

echo " | The-Link:$the_link";
if (stripos($the_link, "n_")){
$the_link = str_replace("n_","",$the_link);
$link_tp = "D";
} // endif
else {
$link_tp = "S";
} // end else
echo " | The-Link:$the_link == Link-tp:$link_tp";

The input for $the_link is "n_8"

And the output is :

| The-Link:n_8 | The-Link:n_8 == Link-tp:S

Well I was expecting to get:

| The-Link:n_8 | The-Link:8 == Link-tp: D

Can anyone see what I've done wrong ?

03-23-2009, 07:04 PM
Your problem is this statement: stripos($the_link, "n_"). It evaluates to 0 since the first position of the occurrence of the substring n_ is in position 0 (remember, positions in strings and arrays begin with 0). In an IF statement, a value of 0 is the same as false, so your str_replace never gets executed.

Try this:

if (stripos($the_link, "n_") !== false){
The !== makes sure that it only checks for boolean false, rather than values like 0 or "".


03-23-2009, 07:04 PM
The big warning in the documentation of the function tells you why you're seeing the results you are:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Change your test to

if (stripos($the_link, "n_") !== FALSE){

and it will work as expected.

03-23-2009, 07:50 PM
Thanks guys for your quick response :thumbsup: