I know the basic method to remove all occurrences of a hyphen (-) :
I have a string that has one or more hyphens multiple times:
and I want to accomplish two things
- Replace all multiple hyphens with one single hyphen,
- Remove hyphens at the beginning and at the end.
The result should be:
Thanks for any ideas.
string.replace(/^-+|-+$/gi,'') will replace all hyphens at beginning and end of string.
string.replace(/-+/gi,'-') will replace one or more hyphens with a single hyphen, globally.
Using either without the global attribute will remove only the first occurrence of hyphen.
EDIT: I should have made a little bit more research before asking. Anyway here is the solution in case someone else needs the same thing:
If I am not wrong,
[-] : means to replace a hyphen
[-]+ : means to replace one or more hyphens (-, --, ---)
/[-]+/g : means to replace multiple occurrences of one or more hyphens as in my sample string above.
Thank you, Wolf, just saw your post after posting mine May I ask what does "i" do? Your code also works without "i".
Yet another solution:
$str = "---this-is-my--string----that-i--want---to-change-";
echo $x = trim( str_replace('--', '-', $str ), '-' );
// trim removes '-' from front and back of $str
Whoops, sorry about not being PHP.
This topic is now closed. New replies are no longer allowed.