10

$str is some value in a foreach.

$str = str_replace('_name_','_title_',$str);

how to make a if str_replace?

I want do the thing if have a str_replace then echo $str, else not, jump the current foreach then to the next. Thanks.

fish man
  • 2,666
  • 21
  • 54
  • 94

3 Answers3

37

There is a fourth parameter to str_replace() that is set to the number of replacements performed. If nothing was replaced, it's set to 0. Drop a reference variable there, and then check it in your if statement:

foreach ($str_array as $str) {
    $str = str_replace('_name_', '_title_', $str, $count);

    if ($count > 0) {
        echo $str;
    }
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
6

If you need to test whether a string is found within another string, you can like this.

<?php
if(strpos('_name_', $str) === false) {
    //String '_name_' is not found
    //Do nothing, or you could change this to do something
} else {
    //String '_name_' found
    //Replacing it with string '_title_'
    $str = str_replace('_name_','_title_',$str);
}
?>

http://php.net/manual/en/function.strpos.php

However you shouldn't need to, for this example. If you run str_replace on a string that has nothing to replace, it won't find anything to replace, and will just move on without making any replacements or changes.

Good luck.

BBB
  • 421
  • 1
  • 5
  • 11
  • 3
    strpos has to have the haystack first. This is correct: (strpos($str, '_name_') === false) – RPL Jun 18 '13 at 21:43
3

I know this is an old question, but it gives me a guideline to solve my own checking problem, so my solution was:

$contn = "<p>String</p><p></p>";
$contn = str_replace("<p></p>","",$contn,$value);
if ($value==0) {
$contn = nl2br($contn);
}

Works perfectly for me. Hope this is useful to someone else.

Samuel Ramzan
  • 1,770
  • 1
  • 15
  • 24