0

If I want to extract only "7.20" from "$ 7.20", how can I do?? I have try

preg_replace("[^0-9]", "", "$ 7.20");

but it is not work. It also shows $ 7.20... There is no difference...

0

2 Answers 2

4
preg_replace('/[^.0-9]/', "", "$ 7.20");

Your regex needs to be delimited, start and end. Commonly / is used as a delimiter.

What you have above: [^0-9]

The initial [ will be interpreted as a delimiter (in pair with ] at the end).

This was looking to replace 0-9 literally at the beginning of the string.

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

2 Comments

You can use brackets as delimiters, so [] is actually okay, like ().
@hakre Gosh, I never noticed that before. Right you are. Thanks for the edit.
2

You could also try sscanf, usually easier to use

sscanf( '$ 7.20', '$ %f' );

1 Comment

With ltrim() and a character mask of $ you can easily remove the leading unwanted characters. In addition to being brief and correct, sscanf() is more powerful than other techniques because it allows you to cast the matched substring as a float.

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.