如何删除字符串中第一个特定字符之前的所有内容?

And*_*rej 10 php string replace

我的变量看起来像这样:

AAAAAAA,BB CCCCCCCC

AAAA,BBBBBB CCCCCC

我想在" ," 之前删除所有内容,

所以结果应该是这样的:

BB CCCCCCCC

BBBBBB CCCCCC

我已经解决了这个问题,以删除" ," 之后的所有内容:

list($xxx) = explode(',', $yyyyy);
Run Code Online (Sandbox Code Playgroud)

不幸的是,我不知道如何让它去除" ," 之前的一切.

And*_*ore 25

由于这是一个简单的字符串操作,您可以使用以下内容删除第一个逗号之前的所有字符:

$string = preg_replace('/^[^,]*,\s*/', '', $input);
Run Code Online (Sandbox Code Playgroud)

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认同)

Tim*_*per 20

我不建议使用explode,因为如果有多个逗号会导致更多问题.

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

编辑:

if(($pos = strpos($str, ',')) !== false)
{
   $new_str = substr($str, $pos + 1);
}
else
{
   $new_str = get_last_word($str);
}
Run Code Online (Sandbox Code Playgroud)