替换字符串的最后一个字符

问题描述:

I've got some entries that I'd like to check last char if is "s" and replace them if that is the case (UTF-8 though).

So for example I've got various strings:

$first = "Pass";
$second = "Jacks Inventory";
$third = "First Second Third etc";

I want it to look each word if the last char is "s" for example to replace it with "n". I am not sure which is the best way to do that.

I know I can grab the last char of the string with the following code (not sure if that is the best way still):

mb_substr($string,-1,1,'UTF-8');

But that won't do it for each word the string has.

You can use preg_replace() with the regex /s\b/, as preg_replace("/s\b/", "n", $string):

<?php

$first = "Pass";
$second = "Jacks Inventory";
$third = "First Second Third etc";

// Alter depending on how you want to combine / loop over the strings
$string = $first . " " . $second . " " . $third;

echo preg_replace("/s\b/", "n", $string);
// Pasn Jackn Inventory First Second Third etc

This can be seen working here.

You can use preg_replace and use the word boundary \b and find words that end with s and replace with n.

$arr =["Pass","Jacks Inventory", "First Second Third etc"];

foreach($arr as $val){
    echo preg_replace("/\b(\w+)(s)\b/", "$1n", $val) . "
";
}

Outputs

Pasn
Jackn Inventory
First Second Third etc

https://3v4l.org/KQvGF

Adding to the answers, Here is a No-Regex Demo

     <?php
     $gotten=array();

     $first = "Pass";
     $second = "Jacks Inventory";
     $third = "First Second Third etc";

     // No Idea How You Get the Strings, Anyway Get It into an array

     if(!in_array($first, $gotten)){
        array_push($gotten, $first);
     }

     if(!in_array($second, $gotten)){
        array_push($gotten, $second);
     }

     if(!in_array($third, $gotten)){
        array_push($gotten, $third);
    }

    for($g=0; $g<count($gotten); $g++){

       $phrase=$gotten[$g];
       $lastChar=mb_substr($phrase, -1,1,'UTF-8');

       echo($phrase . "<br>");

       if($lastChar === "s"){
          echo("Yes". "<br>");
          $newStrr=substr($phrase,0,strlen($phrase)-1)  . "n" . " (altered)";
       }else{      
          echo("No". "<br>");
          $newStrr=$phrase . " (Not Altered)" ; 
       }
       echo($newStrr . "<br>--------------------<br>");

    }

?>