开发者

Returning only 0-9 and dashes from string

开发者 https://www.devze.com 2023-01-28 05:05 出处:网络
I would like to take a string, and strip any characters apart from 0-9 and - (dashes). Example: if I have a strin开发者_如何学JAVAg that looks like:

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

Example:

if I have a strin开发者_如何学JAVAg 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 ?


$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.


Assuming your data is in $string, this will remove all characters except for dashes and digits

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

精彩评论

暂无评论...
验证码 换一张
取 消