开发者

php how to make a if str_replace?

$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开发者_JAVA技巧_replace then echo $str, else not, jump the current foreach then to the next. Thanks.


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;
    }
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜