我的變量是這樣的:第一前在字符串中刪除所有 「」
AAAAAAA,BB CCCCCCCC
AAAA,BBBBBB CCCCCC
我想刪除一切之前「,」
結果應該看起來像:
BB CCCCCCCC
BBBBBB CCCCCC
我已經制定了這去除一切後, 「」:
list($xxx) = explode(',', $yyyyy);
不幸的是我不知道如何得到它的工作,除去一切都在之前「,」
謝謝!
我的變量是這樣的:第一前在字符串中刪除所有 「」
AAAAAAA,BB CCCCCCCC
AAAA,BBBBBB CCCCCC
我想刪除一切之前「,」
結果應該看起來像:
BB CCCCCCCC
BBBBBB CCCCCC
我已經制定了這去除一切後, 「」:
list($xxx) = explode(',', $yyyyy);
不幸的是我不知道如何得到它的工作,除去一切都在之前「,」
謝謝!
我不推薦使用爆炸,因爲它會導致更多的問題,如果有一個以上的逗號。
// 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);
}
這是你應該使用的,恕我直言 – droope 2011-03-16 18:22:59
+1 - 它比正則表達式更快,更可讀(恕我直言)。去這個吧。 – Carpetsmoker 2011-03-16 18:24:14
感謝這工作得很好! – Andrej 2011-03-16 18:24:27
list(,$xxx) = explode(',', $yyyyy, 2);
由於這是一個簡單的字符串操作,您可以使用下面的第一個逗號之前刪除所有字符:
$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
試試這個它得到的最後的東西之後,如果沒有,存在它將檢查從最後一個空間,我將它包裝在一個功能中以方便使用:
<?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);
?>
這個效果不錯!但是我怎麼能告訴腳本在沒有「,」的情況下使用字符串的最後一個單詞? – Andrej 2011-03-16 18:35:25
正則表達式通常很貴,我不會推薦它這樣簡單的東西。 使用explode並將其限制爲2可能會導致與使用str_pos相同的執行時間,但您不必執行任何其他操作來生成所需的字符串,因爲它存儲在第二個索引中。
//simple answer
$str = explode(',', $yyyyy,2)[1];
OR
//better
$arr = explode(',', $yyyyy,2);
$str = isset($arr[1]) ? $arr[1] : '';
你可能會發現['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