7

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

2
  • 1
    So all these yield 100, right? What happens to 1abc00? Commented Jan 9, 2011 at 13:48
  • 1
    Better yet - what about £1.00? Commented Jan 9, 2011 at 13:52

4 Answers 4

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

the ^ inside the [ ] means anything except the following

Edit removed superfluous +

Sign up to request clarification or add additional context in comments.

2 Comments

why not use \D out of curiosity... ? many answers on web use non-number rather than the built-in "not digit"
@nicorellius I wrote this real quick when I answered so didn't really think to use it is all, and haven't thought of it since to edit it to use \d. Though it is more readable for people without a good knowledge of the different regex options.
8
$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

Comments

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

4 Comments

This gives 100 for Boltclock's example, too.
you need the + otherwise it will only replace the first non-number
No, that is partially true for preg_match but not for preg_replace. Just like any normal replace preg_replace replaces each occurence of a character that is [^0-9] with nothing and then continues its search with the next character.
@Patrick - if that was the case, it would fail on acb100def - the solution would be the /g flag. That's true for JavaScript, but not in PHP.
0

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

1 Comment

Note that \D is the same as [^\d]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.