if 语句中 str_replace 出现问题

发布于 2024-12-05 15:54:23 字数 366 浏览 0 评论 0原文

我在 if 语句中使用 str_replace 时遇到一些问题。我想从我输出的某些文本中删除复数格式。

我提供了文本输出中包含的关键字。因此,如果我的关键字的最后一个字符是“s”,我希望从输出中删除复数字符。例如,如果关键字是“手袋”,我想回应“我喜欢手袋”而不是“我喜欢手袋”。这是我想出来的,但它不起作用。

<?php
$keyword = "handbags";

$string = "I love $keyword's.";

$last = substr($keyword, -1);

if ($last == "s") {str_replace("'s", "", $string);}

echo $string;
?>

I'm having some trouble using str_replace within an if statement. I'm wanting to remove plural formatting ('s) from some text I'm outputting.

I supply a keyword that is included with the text output. So if my keyword has an 's' as the last character I want the plural characters stripped from the output. For example if the keyword is 'handbags' I'm wanting to echo "I love handbags" rather than "I love handbags's". This is what I've come up with but it does not work.

<?php
$keyword = "handbags";

$string = "I love $keyword's.";

$last = substr($keyword, -1);

if ($last == "s") {str_replace("'s", "", $string);}

echo $string;
?>

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

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

发布评论

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

评论(5

靖瑶 2024-12-12 15:54:23

if ($last == "s") { $string = str_replace("'s", "", $string);}

if ($last == "s") { $string = str_replace("'s", "", $string);}

猫七 2024-12-12 15:54:23

str_replace 返回一个值,并且不会通过引用作用于字符串。您需要将结果分配回字符串:

$string = str_replace("'s", "", $string);

str_replace returns a value and does not act on the string by reference. You need to assign the result back to the string:

$string = str_replace("'s", "", $string);
べ映画 2024-12-12 15:54:23

您还可以使用:

$string = "I love $keyword".(substr($keyword, -1)=="s"?".":"'s.");

为您节省几行代码:)

You can also use:

$string = "I love $keyword".(substr($keyword, -1)=="s"?".":"'s.");

saves you a couple lines of code :)

浅笑依然 2024-12-12 15:54:23

这是正确的变体:

    <?php
$keyword = "handbags";

$string = "I love $keyword's.";

$last = substr($keyword, -1);

if ($last == "s") {$string=str_replace("'s", "", $string);}

echo $string;
?>

This is correct variant:

    <?php
$keyword = "handbags";

$string = "I love $keyword's.";

$last = substr($keyword, -1);

if ($last == "s") {$string=str_replace("'s", "", $string);}

echo $string;
?>
倥絔 2024-12-12 15:54:23

这应该可以解决问题

$keyword = "handbag";
$string = "I love $keyword";

$string_count = strlen($string)-1;
$string_check = substr($string,$string_count,1); 

if($string_check == "s"){
    $string = str_replace("s", "'s", $string);
    echo "$string.";
    }
    else {
    echo $string."'s.";
}

This should do the trick

$keyword = "handbag";
$string = "I love $keyword";

$string_count = strlen($string)-1;
$string_check = substr($string,$string_count,1); 

if($string_check == "s"){
    $string = str_replace("s", "'s", $string);
    echo "$string.";
    }
    else {
    echo $string."'s.";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文