我的字符串看起来像这样:
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 :(得分:20)
答案 1 :(得分: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
答案 2 :(得分: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"
我以为我会把它扔出去作为一个奇怪的选择。
答案 3 :(得分:1)
$string="Bob Mackey-O'Donnell - Name: bmackeyodonnell";
$parts=explode("- Name:",$string);
$name=$parts[0];
虽然我的解决方案更好......
答案 4 :(得分:0)
更清洁的方式:
$find = 'Name';
$fullString = 'aoisdjaoisjdoisjdNameoiasjdoijdsf';
$output = strstr($fullString, $find, true) . $find ?: $fullString;