php 如何制作 if str_replace?

发布于 2024-11-14 01:48:11 字数 245 浏览 1 评论 0原文

$str 是 foreach 中的某个值。

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

如何制作if str_replace

我想做的事情如果有一个str_replace然后回显$str,否则不,跳转当前的foreach然后到下一个。谢谢。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

人海汹涌 2024-11-21 01:48:11

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

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

    if ($count > 0) {
        echo $str;
    }
}

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;
    }
}
墟烟 2024-11-21 01:48:11

如果您需要测试一个字符串是否在另一个字符串中找到,您可以这样做。

<?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

但是,对于本例来说,您不需要这样做。如果您在没有任何可替换内容的字符串上运行 str_replace,它将找不到任何可替换内容,并且只会继续前进,而不进行任何替换或更改。

祝你好运。

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.

Bonjour°[大白 2024-11-21 01:48:11

我知道这是一个老问题,但它为我提供了解决我自己的检查问题的指南,所以我的解决方案是:

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

非常适合我。
希望这对其他人有用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文