Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning only 0-9 and dashes from string

Tags:

string

regex

php

I would like to take a string, and strip any characters apart from 0-9 and - (dashes).

Example:

if I have a string that looks like:

10-abc20-30

How can I make this string return

10-20-30

(Strip all characters besides numbers and dashes)

Is there some kind of regex to use within preg_match or str_replace ?

like image 373
DevNull Avatar asked Dec 05 '10 08:12

DevNull


1 Answers

$result = preg_replace('/[^\d-]+/', '', $subject);

[^\d-] matches any character except digits or dash; the + says "one or more" of those, so adjacent characters will be replaced at once.

like image 184
Tim Pietzcker Avatar answered Oct 17 '22 22:10

Tim Pietzcker