删除字符串后面的字符?

8

我有一些长这样的字符串:

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

所以,基本上我正在尝试找到一种方法,在“- Name:”之前截断它。我一直在使用substr和preg_replace进行尝试,但似乎无法得到我希望得到的结果...有人能帮忙吗?


会有一个 John Miller - Doe - Name: 吗?最后总会有 Name: 吗? - Pekka
你可能会发现s($str)->beforeLast('-')很有用,这是在这个独立库中找到的。 - caw
5个回答

21

假设这些字符串始终具有此格式,则其中一种可能是:

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

参考文献:substrstrpos


7
使用模式/ - Name:.*/preg_replace()函数:
<?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

非常感谢,这个答案可以用于任何字符串。 - peter.o

2
在第二个连字符之前的所有内容,是吗?一种方法是:
$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"

我觉得这是一个奇怪的替代方案,只是随口一提。

谢谢分享,伙计。我喜欢这种方式,它对我很有效! - Sagive

1
$string="Bob Mackey-O'Donnell - Name: bmackeyodonnell";
$parts=explode("- Name:",$string);   
$name=$parts[0];

尽管在我的解决方案之后的解决方案更加好看...


0
更清晰的方式:
$find = 'Name';
$fullString = 'aoisdjaoisjdoisjdNameoiasjdoijdsf';
$output = strstr($fullString, $find, true) . $find ?: $fullString;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接