php 删除字符串后的字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3991843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove characters after string?
提问by KarmaKarmaKarma
I have strings that looks like this:
我有看起来像这样的字符串:
John Miller-Doe - Name: jdoe
Jane Smith - Name: jsmith
Peter Piper - Name: ppiper
Bob Mackey-O'Donnell - Name: bmackeyodonnell
I'm trying to remove everything after the second hyphen, so that I'm left with:
我试图删除第二个连字符后的所有内容,以便我留下:
John Miller-Doe
Jane Smith
Peter Piper
Bob Mackey-O'Donnell
So, basically, I'm trying to find a way to chop it off right before "- Name:". I've been playing around with substr and preg_replace, but I can't seem to get the results I'm hoping for... Can someone help?
所以,基本上,我试图找到一种方法在“-名称:”之前将其切断。我一直在玩 substr 和 preg_replace,但我似乎无法得到我希望的结果......有人可以帮忙吗?
回答by Felix Kling
回答by Jeremy W. Sherman
Use preg_replace()
with the pattern / - Name:.*/
:
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";
?>
Output:
输出:
result: John Miller-Doe
Jane Smith
Peter Piper
Bob Mackey-O'Donnell
回答by JAL
Everything after right before the second hyphen then, correct? One method would be
紧接着第二个连字符之前的所有内容,对吗?一种方法是
$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"
Just thought I'd throw that out there as a bizarre alternative.
只是想我会把它作为一个奇怪的选择扔在那里。
回答by FatherStorm
$string="Bob Mackey-O'Donnell - Name: bmackeyodonnell";
$parts=explode("- Name:",$string);
$name=$parts[0];
Though the solution after mine is much nicer...
虽然我之后的解决方案要好得多......
回答by Hyman
A cleaner way:
更干净的方法:
$find = 'Name';
$fullString = 'aoisdjaoisjdoisjdNameoiasjdoijdsf';
$output = strstr($fullString, $find, true) . $find ?: $fullString;