dongruidian3064
dongruidian3064
2018-08-19 20:42

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

已采纳

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dr200166 dr200166 3年前

    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.

    点赞 评论 复制链接分享
  • dongyaofu0599 dongyaofu0599 3年前

    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>");
    
        }
    

    ?>

    点赞 评论 复制链接分享
  • douqiao6563 douqiao6563 3年前

    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

    点赞 评论 复制链接分享