11

$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.

3 Answers 3

39

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

strpos has to have the haystack first. This is correct: (strpos($str, 'name') === false)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.