【问题标题】:Remove characters after string?删除字符串后的字符?
【发布时间】:2011-04-28 20:33:27
【问题描述】:

我的字符串看起来像这样:

John Miller-Doe - Name: jdoe
Jane Smith - Name: jsmith
Peter Piper - Name: ppiper
Bob Mackey-O'Donnell - Name: bmackeyodonnell

我正在尝试删除第二个连字符后的所有内容,因此我只剩下:

John Miller-Doe
Jane Smith
Peter Piper
Bob Mackey-O'Donnell

所以,基本上,我正在尝试找到一种方法在“-名称:”之前将其切断。我一直在玩 substr 和 preg_replace,但我似乎无法得到我希望的结果......有人可以帮忙吗?

【问题讨论】:

标签: php string replace


【解决方案1】:

假设字符串总是具有这种格式,一种可能性是:

$short = substr($str, 0, strpos( $str, ' - Name:'));

参考:substrstrpos

【讨论】:

    【解决方案2】:

    preg_replace()/ - Name:.*/ 模式一起使用:

    <?php
    $text = "John Miller-Doe - Name: jdoe
    Jane Smith - Name: jsmith
    Peter Piper - Name: ppiper
    Bob Mackey-O'Donnell - Name: bmackeyodonnell";
    
    $result = preg_replace("/ - Name:.*/", "", $text);
    echo "result: {$result}\n";
    ?>
    

    输出:

    result: John Miller-Doe 
    Jane Smith 
    Peter Piper 
    Bob Mackey-O'Donnell
    

    【讨论】:

    • 非常感谢,这个答案可以用于任何字符串。
    【解决方案3】:

    那么在第二个连字符之前的所有内容,对吗?一种方法是

    $string="Bob Mackey-O'Donnell - Name: bmackeyodonnel";
    $remove=strrchr($string,'-');
    //remove is now "- Name: bmackeyodonnell"
    $string=str_replace(" $remove","",$string);
    //note $remove is in quotes with a space before it, to get the space, too
    //$string is now "Bob Mackey-O'Donnell"
    

    只是想我会把它作为一个奇怪的选择扔在那里。

    【讨论】:

    • 感谢分享伙伴。我喜欢这种方式,它对我有用!
    【解决方案4】:
    $string="Bob Mackey-O'Donnell - Name: bmackeyodonnell";
    $parts=explode("- Name:",$string);   
    $name=$parts[0];
    

    虽然我的解决方案要好得多......

    【讨论】:

      【解决方案5】:

      更清洁的方式:

      $find = 'Name';
      $fullString = 'aoisdjaoisjdoisjdNameoiasjdoijdsf';
      $output = strstr($fullString, $find, true) . $find ?: $fullString;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-18
        • 2011-12-15
        • 2015-11-20
        • 1970-01-01
        • 2017-02-22
        • 2010-12-20
        • 1970-01-01
        相关资源
        最近更新 更多