views:

36

answers:

4

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?

+1  A: 

$parts=explode("- Name:",$string);
name=$parts[0];

though the solution after mine is much nicer...

FatherStorm
+3  A: 

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

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

Reference: substr, strpos

Felix Kling
A: 

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.

Alex JL
+2  A: 

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
Jeremy W. Sherman