2010-10-21 168 views
7

我有一个字符串,看起来像这样:删除字符串后的字符?

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,但我似乎无法得到我期待的结果...有人可以帮忙吗?

+0

才会有'约翰·米勒 - 伊 - 名称:' ?最后总是会有'Name:'? – 2010-10-21 21:00:34

+0

你可能会发现['s($ str) - > beforeLast(' - ')'](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L399)如[独立库](https://github.com/delight-im/PHP-Str)中所示。 – caw 2016-07-27 03:39:59

回答

19

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

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

参考:substrstrpos

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

虽然之后我的解决办法是好多了...

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" 

只是想我会抛出那里作为一个奇怪的选择。

+0

感谢分享伴侣。我喜欢这种方式,它适用于我! – 2013-10-10 04:18:56

7

使用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 
+0

非常感谢,这个答案可以用于任何字符串。 – 2014-05-15 13:50:30

0

一个更清洁的方式:

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