Return only 0-9 and dashes from string

I would like to take a string and delete any characters except 0-9 and - (dash).

Example:

if I have a line that looks like this:

10-abc20-30

How can I return this line

10-20-30

(separate all characters except numbers and dashes)

Is there any regular expression to use in preg_match or str_replace?

+6
string php regex
source share
2 answers
$result = preg_replace('/[^\d-]+/', '', $subject); 

[^\d-] matches any character except digits or dashes; + says "one or more" of them, so adjacent characters will be replaced immediately.

+11
source share

Assuming your data is in $ string, this will delete all characters except dashes and numbers

 $string = preg_replace('/[^-0-9]/', null, $string); 
+2
source share

All Articles