2011-03-16 45 views
8

我的變量是這樣的:第一前在字符串中刪除所有 「」

AAAAAAA,BB CCCCCCCC

AAAA,BBBBBB CCCCCC

我想刪除一切之前「,」

結果應該看起來像:

BB CCCCCCCC

BBBBBB CCCCCC

我已經制定了這去除一切後, 「」:

list($xxx) = explode(',', $yyyyy); 

不幸的是我不知道如何得到它的工作,除去一切都在之前「,」

謝謝!

+0

你可能會發現['S($ STR) - > afterFirst( '')'](https://github.com/delight-im/PHP-Str /blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L435)很有幫助,在[此獨立庫](https://github.com/delight-im/PHP-Str)中找到。 – caw 2016-07-27 03:55:50

回答

15

我不推薦使用爆炸,因爲它會導致更多的問題,如果有一個以上的逗號。

// removes everything before the first , 
$new_str = substr($str, ($pos = strpos($str, ',')) !== false ? $pos + 1 : 0); 

編輯:

if(($pos = strpos($str, ',')) !== false) 
{ 
    $new_str = substr($str, $pos + 1); 
} 
else 
{ 
    $new_str = get_last_word($str); 
} 
+0

這是你應該使用的,恕我直言 – droope 2011-03-16 18:22:59

+0

+1 - 它比正則表達式更快,更可讀(恕我直言)。去這個吧。 – Carpetsmoker 2011-03-16 18:24:14

+0

感謝這工作得很好! – Andrej 2011-03-16 18:24:27

1

你可以這樣做:

$arr = explode(',', $yyyyy); 
unset($arr[0]); 
echo implode($arr); 
+0

我覺得這很好。雖然你需要回聲implode(',',$ arr);不要失去其他的逗號。 – embe 2014-12-11 10:37:55

+0

@embe問題示例中沒有其他逗號 – Neal 2014-12-11 10:56:51

+0

是真的。這是我的情況,並回答「刪除第一個之前的一切」,「在一個字符串中」我認爲這是很好的補充。感謝您提供一個好的解決方案。 – embe 2014-12-11 11:11:56

1
list(,$xxx) = explode(',', $yyyyy, 2); 
25

由於這是一個簡單的字符串操作,您可以使用下面的第一個逗號之前刪除所有字符:

$string = preg_replace('/^[^,]*,\s*/', '', $input); 

preg_replace()允許您可以根據正則表達式替換部分字符串。我們來看看正則表達式。

  • / is the start delimiter
    • ^ is the "start of string" anchor
    • [^,] every character that isn't a comma (^ negates the class here)
      • * repeated zero or more times
    • , regular comma
    • \s any whitespace character
      • * repeated zero or more times
  • / end delimiter
+2

正則表達式是你的朋友 – Canuteson 2011-03-16 18:27:20

+0

如果我想刪除**之前的每個字符並且包含**逗號? – 2016-02-16 16:07:59

+0

我一直在尋找相同的結果通過用''替換'''','所以完整的代碼將變成:'$ string = preg_replace('/^[^,] *,\ s * /',',',$ input);' – hyip 2016-03-10 14:52:48

2

試試這個它得到的最後的東西之後,如果沒有,存在它將檢查從最後一個空間,我將它包裝在一個功能中以方便使用:

<?php 
$value='AAAA BBBBBB CCCCCC'; 
function checkstr($value){ 
    if(strpos($value,',')==FALSE){ 
     return trim(substr(strrchr($value, ' '), 1)); 
    }else{ 
     return trim(substr($value, strpos($value,',')),','); 
    } 
} 

echo checkstr($value); 
?> 
+0

這個效果不錯!但是我怎麼能告訴腳本在沒有「,」的情況下使用字符串的最後一個單詞? – Andrej 2011-03-16 18:35:25

0

正則表達式通常很貴,我不會推薦它這樣簡單的東西。 使用explode並將其限制爲2可能會導致與使用str_pos相同的執行時間,但您不必執行任何其他操作來生成所需的字符串,因爲它存儲在第二個索引中。

//simple answer 
$str = explode(',', $yyyyy,2)[1]; 

OR

//better 

$arr = explode(',', $yyyyy,2); 
$str = isset($arr[1]) ? $arr[1] : ''; 
相關問題