开发者

Remove characters after string?

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 af开发者_开发百科ter 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?


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

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

Reference: substr, strpos


Use preg_replace() with the pattern / - 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


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.


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

Though the solution after mine is much nicer...


A cleaner way:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜