nayen — 2014-05-09T09:20:49-04:00 — #1
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.
wolfshade — 2014-05-09T09:35:16-04:00 — #2
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.
nayen — 2014-05-09T09:37:34-04:00 — #3
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".
john_betong — 2014-05-09T12:45:46-04:00 — #4
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
wolfshade — 2014-05-09T12:56:50-04:00 — #5
john_betong — 2014-05-09T13:14:35-04:00 — #6
Whoops, sorry about not being PHP.