2012-03-07 142 views
18

我想搜索和PHP中的另一個替換的第一個字就像如下:PHP替換字符串的第一次出現,從第0位

$str="nothing inside"; 

通過搜索替換「什麼」到「東西」,並且不使用替代substr

輸出應該是:「裏面的東西」

+0

爲什麼沒有substr? – lfxgroove 2012-03-07 09:27:37

+1

[使用str \ _replace以便它只對第一個匹配起作用]的可能的重複?(http://stackoverflow.com/questions/1252693/using-str-replace-so-that-it-only-acts-on - 第一次匹配) – Bas 2015-04-24 14:08:25

回答

35

使用preg_replace()爲1的限制:

preg_replace('/nothing/', 'something', $str, 1); 

更換正則表達式/nothing/您要搜索的任何字符串。由於正則表達式總是從左到右進行計算,因此它將始終與第一個實例匹配。

+3

如果您只是使用通用字符串,則此解決方案存在轉義問題,例如$和$等字符串在該字符串中。 http://stackoverflow.com/questions/1252693/php-str-replace-that-only-acts-on-the-first-match有一個更通用的解決方案。 – Anther 2012-10-17 18:55:37

0

This function str_replace是你正在尋找的人。

+6

第4個參數計數替換次數,不限制替換次數 – mishu 2012-03-07 09:25:26

+0

您是對的。將編輯我的答案。 – steveoh 2012-03-07 09:27:07

+0

@steveoh:str_replace替換所有發生,但我只想要第一次出現,如果它在開始像ltrim函數一樣存在,請僅刪除第一個空格。 – Ben 2012-03-07 09:30:33

2
preg_replace('/nothing/', 'something', $str, 1); 
+0

這將取代所有發生。 preg_replace('/ OR /','',$ str,1)替換第一次出現的'OR',但不僅僅是領先的出現 – Ben 2012-03-07 09:42:55

3

試試這個

preg_replace('/^[a-zA-Z]\s/', 'ReplacementWord ', $string) 

它的作用是從開始選擇任何內容,直到第一白色空間和replcementWord更換。在replcementWord之後注意一個空格。這是因爲我們在搜索字符串

+0

我也不如regEx。你可以試試這個鏈接[所以你想學習正則表達式?](http://www.stedee.id.au/Learn_Regular_Expressions) – 2012-03-07 09:34:08

+0

對不起,但我無法正確格式化 – 2012-03-07 09:34:58

10

添加\s的str_replace函數(http://php.net/manual/en/function.str-replace.php)的男子頁面上,你可以找到這個功能

function str_replace_once($str_pattern, $str_replacement, $string){ 

    if (strpos($string, $str_pattern) !== false){ 
     $occurrence = strpos($string, $str_pattern); 
     return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern)); 
    } 

    return $string; 
} 

使用示例:http://codepad.org/JqUspMPx

+0

與preg_replace('/ search /','replace',$ str,1)相同。 – Ben 2012-03-07 10:05:10

+2

@Ben功能是相似的,但絕對不一樣。如果您使用需要通過正則表達式轉義的字符,則在使用preg_replace時會發生意外錯誤。 – Anther 2012-10-17 19:54:05

+0

@mishu整天浪費,然後我找到了你的答案,謝謝哥們。 – 2015-05-14 16:20:54

-1

ltrim()將刪除字符串開頭的不需要的文本。

$do = 'nothing'; // what you want 
$dont = 'something'; // what you dont want 
$str = 'something inside'; 
$newstr = $do.ltrim($str , $dont); 
echo $newstr.'<br>'; 
+0

ltrim()刪除給定列表中的所有字符,而不是字符序列。請更新您的答案。 – Calin 2013-08-22 09:35:53

0

我跑到這個問題,需要的解決方案,這是不是100%適合我,因爲如果字符串像$str = "mine'this,該appostrophe會產生問題。所以我想出了一個痘痘絕招:

$stick=''; 
$cook = explode($str,$cookie,2); 
     foreach($cook as $c){ 
      if(preg_match("/^'/", $c)||preg_match('/^"/', $c)){ 
       //we have 's dsf fds... so we need to find the first |sess| because it is the delimiter' 
       $stick = '|sess|'.explode('|sess|',$c,2)[1]; 
      }else{ 
       $stick = $c; 
      } 
      $cookies.=$stick; 
     } 
0

這難道不是最好的緊湊性和性能?

if(($offset=strpos($string,$replaced))!==false){ 
    $string=substr_replace($replaced,$replacer,$offset,strlen($replaced)); 
} 
相關問題