stunnaman
stunnaman

Reputation: 911

How can I convert two or more dashes to singles and remove all dashes at the beginning and end of a string?

Example: -this--is---a-test--

What I want: this-is-a-test

Thanks for any answers! :)

Upvotes: 6

Views: 4305

Answers (2)

John
John

Reputation: 13739

Without regular expression....

$string = trim($string,'-');

while (stristr($string,'--')) {$c = str_ireplace('--','-',$string);}

Upvotes: 0

Gumbo
Gumbo

Reputation: 655329

I would use a combination of preg_replace and trim:

trim(preg_replace('/-+/', '-', $str), '-')

The preg_replace call removes multiple dashes and trim removes the leading and trailing dashes.

Upvotes: 21

Related Questions