簡體   English   中英

如何從php中的字符串中查找和替換第一個單詞

[英]how to find and replace in the first word from the string in php

如何使用php從字符串中查找和替換第一個單詞

例如:

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

預期結果應為“ Super World Hello World”,因為它與第一個單詞不匹配。

eg2:

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

預期結果應為“ Hi World Hello World”,因為它確實與第一個單詞匹配。

請幫忙

為此創建一個函數,傳遞了3個參數。 邏輯是通過explode()函數將字符串轉換為數組,並使用array_shift()函數獲取數組的第一個元素,然后與搜索字符串進行比較

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 "\n";
echo getReplacedStr($str2, $searchStr, $replaceWith);

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM