Remove characters after string?

24,160

Solution 1

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

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

Reference: substr, strpos

Solution 2

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

Solution 3

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.

Solution 4

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

Though the solution after mine is much nicer...

Share:
24,160
KarmaKarmaKarma
Author by

KarmaKarmaKarma

Updated on July 27, 2022

Comments

  • KarmaKarmaKarma
    KarmaKarmaKarma almost 2 years

    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?

  • Sagive
    Sagive over 10 years
    Thanks for sharing mate. i love this way and it works for me!
  • peter.o
    peter.o about 10 years
    Thanks a lot, this answer could be use for any string.