【问题标题】:How to remove everything before the first specific character in a string?如何删除字符串中第一个特定字符之前的所有内容?
【发布时间】:2011-07-16 20:05:24
【问题描述】:

我的变量如下所示:

AAAAAAA,BB CCCCCCCC

AAAA,BBBBBB CCCCCC

我想删除“,”之前的所有内容,

所以结果应该是这样的:

BB CCCCCCCC

BBBBBB CCCCCC

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

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

不幸的是,我不知道如何让它工作以删除“,”之前的所有内容。

【问题讨论】:

标签: php string replace


【解决方案1】:

正则表达式通常很昂贵,我不推荐它用于这么简单的事情。 使用 explode 并将其限制为 2 可能会导致与使用 str_pos 相同的执行时间,但您无需执行任何其他操作即可生成所需的字符串,因为它存储在第二个索引中。

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

//better 

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

【讨论】:

    【解决方案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);
    ?>
    

    【讨论】:

    • 这也很好用!但是如果没有“,”,我如何告诉脚本使用字符串的最后一个单词?
    【解决方案3】:

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

    // 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);
    }
    

    【讨论】:

    • 这是你应该使用的,恕我直言
    • +1 -- 它比正则表达式更快、更易读(恕我直言)。去吧。
    • @Carpetsmoker:但是当没有任何逗号时,这会失败。 strpos() 在没有逗号时返回 false,false + 1 = 1 这意味着你最终会剥离你的第一个字符。
    • @Andrew:已修复,因此如果没有逗号,它不会失败。我确实更喜欢您的正则表达式解决方案。
    • 像下面的例子一样使用 trim()
    【解决方案4】:

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

    $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

    【讨论】:

    • 正则表达式是你的朋友。
    • 如果我想删除 之前的每个字符并包括 逗号怎么办?
    • 我一直在寻找相同的。最后将'' 替换为',',这样完整的代码将变为:$string = preg_replace('/^[^,]*,\s*/', ',', $input);
    【解决方案5】:
    list(,$xxx) = explode(',', $yyyyy, 2);
    

    【讨论】:

    • 另外:$xxx = explode(',', $yyyyy, 2)[1];.
    【解决方案6】:

    你可以这样做:

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

    【讨论】:

    • 我觉得这很好。虽然你需要回显 implode(',',$arr);不要丢失其他逗号。
    • @embe 问题示例中没有其他逗号
    • 是的。就我而言,回答“删除字符串中第一个“,”之前的所有内容”我认为添加它很好。感谢您提供好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多