Delete characters after line?

I have lines that look like this:

John Miller-Doe - Name: jdoe Jane Smith - Name: jsmith Peter Piper - Name: ppiper Bob Mackey-O'Donnell - Name: bmackeyodonnell 

I try to delete everything after the second hyphen, so I have left:

 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 played with substr and preg_replace, but I can’t get the results that I hope for ... Can someone help?

+7
string php replace
source share
5 answers

Assuming strings will always have this format, one of the possibilities is:

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

Link: substr , strpos

+19
source share

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 
+7
source share

Everything that happened right before the second defem then, right? One method is

 $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 that I would throw it as a strange alternative.

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

Although the solution after my work is much better ...

+1
source share

Cleaner way:

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

All Articles