drs
drs

Reputation: 1265

preg_replace - strip unwanted characters from string to return numeric value

I hate regular expressions and I was hoping someone could help with a regualar expression to be used with preg_replace.

I want to strip unwanted characers from a string to return just a numeric value using preg_replace.

The string format could be as follows:

SOME TEXT £100

£100 SOME TEXT

SOME TEXT 100 SOME TEXT

Many thanks

Upvotes: 7

Views: 19841

Answers (4)

Patrick Evans
Patrick Evans

Reputation: 42746

$NumericVal = preg_replace("/[^0-9]/","",$TextVariable);

the ^ inside the [ ] means anything except the following

Edit removed superfluous +

Upvotes: 17

user956584
user956584

Reputation: 5558

$l = preg_replace("/[^A-Z0-9a-z\w ]/u", '', $l);

Works witch UTF-8, allow only A-Z a-z 0-9 łwóc... etc

Upvotes: 8

Kobi
Kobi

Reputation: 138147

Try this:

preg_replace("/\D+/", "", "SOME TEXT £100")

You can also use preg_match to get the first number:

preg_match("/\d+/", "SOME TEXT £100", $matches);
$number = $matches[0];

Upvotes: 0

AndreKR
AndreKR

Reputation: 33707

preg_replace('/[^0-9]/','',$text);

Upvotes: 0

Related Questions