Reputation: 451
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;
?>
Upvotes: 0
Views: 1509
Reputation: 681
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.";
}
Upvotes: 0
Reputation: 510
You can also use:
$string = "I love $keyword".(substr($keyword, -1)=="s"?".":"'s.");
saves you a couple lines of code :)
Upvotes: 2
Reputation: 3572
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;
?>
Upvotes: 1
Reputation: 8003
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);
Upvotes: 2