duande1986 2018-03-14 18:37
浏览 240
已采纳

如何在php中的字符串中找到并替换第一个单词

how to find and replace the first word from the string using php

eg:

 $str = 'Super World Hello World';
 replace($str,'Hello','Hi');

expected result should be 'Super World Hello World' as it does not match with first word.

eg2:

 $str = 'Hello World Hello World';
 replace($str,'Hello','Hi');

expected result should be 'Hi World Hello World' as it does match with first word.

please help

  • 写回答

1条回答 默认 最新

  • doushao1948 2018-03-14 18:58
    关注

    Create a function for this, passed 3 arguments. Logic is convert string into array by explode() function and get first element of the array by using array_shift() function and compare with search string

    function getReplacedStr($str, $searchStr, $replaceWith){
        $arr = explode(' ', $str);
    $firstElement = array_shift($arr);
    if($searchStr == $firstElement){
        $finalStr =  $replaceWith.' '.implode(' ', $arr);
    }else{
        $finalStr = $str;
    }
    return $finalStr;
    }
    $replaceWith = 'Hi';
    $searchStr = 'Hello';
    $str = 'Hello World Hello World';
    $str2 = 'Super World Hello World';
    
    echo getReplacedStr($str, $searchStr, $replaceWith);
    echo "
    ";
    echo getReplacedStr($str2, $searchStr, $replaceWith);
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器