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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With