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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:39:56  来源:igfitidea点击:

Remove characters after string?

phpstringreplace

提问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

Assuming that the strings will always have this format, one possibility is:

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

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

Reference: substr, strpos

参考:substrstrpos

回答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;