dongruidian3064 2018-08-19 20:42
浏览 90
已采纳

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

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 2018-08-19 20:49
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?