开发者

How to remove everything before the first specific character in a string?

My variables开发者_开发百科 look like this:

AAAAAAA, BB CCCCCCCC

AAAA,BBBBBB CCCCCC

I would like to remove everything before the ",",

so the results should look like:

BB CCCCCCCC

BBBBBB CCCCCC

I have worked out this to remove everything AFTER the ",":

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

unfortunately I dont know how to get it to work to remove everything BEFORE the ",".


Since this is a simple string manipulation, you can use the following to remove all characters before the first comma:

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

preg_replace() allows you to replace parts of a string based on a regular expression. Let's take a look at the regular expression.

  • / 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


I wouldn't recommend using explode, as it causes more issues if there is more than one comma.

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

Edit:

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


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


try this it gets the last stuff after the , if no , is present it will check from the last space, i wrapped it in a function to make it easy:

<?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);
?>


you can do:

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


Regex is generally expensive and i wouldn't recommend it for something as simple as this. Using explode and limiting it to 2 will probably result in the same execution time as using str_pos but you wouldn't have to do anything else to generate the required string as its stored in the second index.

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

OR

//better 

$arr = explode(',', $yyyyy,2);
$str = isset($arr[1]) ? $arr[1] : '';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜