php如何制作if str_replace?

fis*_*man 6 php str-replace

$str 在foreach中是有价值的.

$str = str_replace('_name_','_title_',$str);
Run Code Online (Sandbox Code Playgroud)

怎么做if str_replace

我想做的事情if have a str_replace然后回声$str,否则,跳过当前的foreach然后到下一个.谢谢.

Bol*_*ock 25

第四个参数str_replace()设置为执行的替换次数.如果没有替换,则将其设置为0.在那里删除一个引用变量,然后在if语句中检查它:

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

    if ($count > 0) {
        echo $str;
    }
}
Run Code Online (Sandbox Code Playgroud)


BBB*_*BBB 6

如果你需要测试是否在另一个字符串中找到了一个字符串,你可以这样.

<?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);
}
?>
Run Code Online (Sandbox Code Playgroud)

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

但是,对于此示例,您不需要.如果你运行str_replace一个没有什么可替换的字符串,它将找不到任何要替换的东西,并且只是继续前进而不进行任何替换或更改.

祝好运.

  • strpos必须首先拥有干草堆。这是正确的:(strpos($ str,'_name_')=== false) (2认同)