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

时间:2018-08-19 20:42:20

标签: php encoding

我有一些条目要检查最后一个字符是否为“ s”,如果是这种情况,则将其替换(不过是UTF-8)。

例如,我有各种字符串:

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

如果最后一个字符为“ s”,我希望它查找每个单词,例如将其替换为“ n”。我不确定哪种方法最好。

我知道我可以使用以下代码来捕获字符串的最后一个字符(不确定这是否仍然是最好的方法):

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

但这不会对字符串中的每个单词都起作用。

3 个答案:

答案 0 :(得分:0)

您可以将 preg_replace() 与正则表达式/s\b/一起使用,作为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

可以在 here 上看到它。

答案 1 :(得分:0)

您可以使用preg_replace并使用边界\b来查找以s结尾并以n代替的单词。

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

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

输出

Pasn
Jackn Inventory
First Second Third etc

https://3v4l.org/KQvGF

答案 2 :(得分:0)

添加到答案中,这是一个无正则表达式演示

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

    }

?>

相关问题