Home » Php » php – preg_replace – strip unwanted characters from string to return numeric value

php – preg_replace – strip unwanted characters from string to return numeric value

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:
$NumericVal = preg_replace("/[^0-9]/","",$TextVariable);

the ^ inside the [ ] means anything except the following

Edit
removed superfluous +

Answer:

$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

Answer:

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

Answer:

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];