开发者

Stripping a string of characters in PHP [duplicate]

开发者 https://www.devze.com 2023-03-12 21:32 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: stripping out all characters from a string, leaving numbers
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

stripping out all characters from a string, leaving numbers

I开发者_StackOverflow社区 have something produced by an API that looks like: 34 Canadian Dollars. I'm trying to get rid of the alphabetical characters and keep only the numeric characters. How can I do that?


$result = preg_replace('/[^0-9\.,]/', '', $input);

HTH.

Edited to accept commas and periods.


Given the fact that you're working with currencies and that the number may contain a comma or decimal point, you should use this instead:

preg_match('/([0-9\.,]+)/', $input, $matches);

// Output the amount.
echo $matches[1];


preg_match would be perfect for this.

preg_match("/^([0-9]*) *$/", $inputStr, $results);
echo $results[1];

Also, this online regex tester is a great place to test out other regex patterns.


If it is an integer you are trying to collect you can use (int) $input


Well, i dont know your purpose, but if numbers are always in the beginning of the string, you can use casting.

$int = (int)"34 Canadian Dollars";

OR

$string = "34 Canadian Dollars";
$number = (int)$string

hope that helps. the preg_replace in the other answer will also do the job.

0

精彩评论

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