Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

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

What I want: this-is-a-test

Thanks for any answers! :)

like image 347
stunnaman Avatar asked Apr 12 '09 10:04

stunnaman


People also ask

How do I remove dashes from a string?

Use the String. replace() method to remove all hyphens from a string, e.g. const hyphensRemoved = str. replace(/-/g, ''); . The replace() method will remove all hyphens from the string by replacing them with empty strings.

How do I remove dashes from a string in Python?

Use the str. replace() method to remove the hyphens from a string, e.g. result = my_str. replace('-', '') .


1 Answers

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.

like image 85
Gumbo Avatar answered Oct 23 '22 20:10

Gumbo