Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 761
KarmaKarmaKarma Avatar asked Oct 21 '10 20:10

KarmaKarmaKarma


People also ask

How do you delete everything after a certain character in a string?

To remove everything after a specific character in a string:Use the String. split() method to split the string on the character. Access the array at index 0 . The first element in the array will be the part of the string before the specified character.

How do I remove unwanted characters from a string?

Removing symbol from string using replace() One can use str. replace() inside a loop to check for a bad_char and then replace it with the empty string hence removing it.

How do I remove part of a string?

We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove. REMOVE(): This function replaces all occurrences of a substring within a new substring.


2 Answers

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

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

Reference: substr, strpos

like image 174
Felix Kling Avatar answered Sep 20 '22 06:09

Felix Kling


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
like image 32
Jeremy W. Sherman Avatar answered Sep 22 '22 06:09

Jeremy W. Sherman