1

I have a very simple textbox given to a user.

<textarea name="text">ENTER YOUR TEXT, DUDE!</textarea>

Sometimes, users could input something like this:

blablablatext blablabla $ 10 blablabla blablablatext

Which is fine but what I want to do is take the dollar symbol and automatically place it after the number (or vice versa):

blablablatext blablabla 10 $ blablabla blablablatext

Basically, what I want to do is:

  1. Detect if there is a currency symbol
  2. Detect if numbers appear right after the symbol
  3. Detect if, for example, a letter (or nothing) appears right after the numbers
  4. Take the currency symbol and place it inbetween the numbers and letters (or just after the numbers if there is nothing afterwards)

What is the best way to do it? Is something like that possible?

4
  • Since you explicitly mentioned "letter appears behind number" in 3rd point, what's the difference between "place the dollar symbol between the number and the letter following it" and "place the dollar symbol behind the number" in your 4th point? Commented Nov 9, 2012 at 7:48
  • In the third point, I only took "letters" as one example. It could be anything other than numbers you could be searching for, words, dots, commas or, like I "kinda" mentioned in the forth point, nothing at all. That's why I said either inbetween the number and, for example, the letter, or just after the number when there is nothing else following the number. Sorry for the confusion, hope that clears it up. I changed my post accordingly. Commented Nov 9, 2012 at 10:53
  • Your 3 and 4 point seems can just combine into one "place the symbol behind the numbers", because whatever (if any) comes behind the numbers seems do not matter. That's why I ask if you mean something by explicitly bringing up the 3rd point. Commented Nov 9, 2012 at 11:18
  • It actually does matter because I don't want to place the currency symbol directly after the number if another number follows after a whitespace. Lets say somebody types some nonsense like "$ 10 10", I don't want to get "10 $ 10", I want to get "10 10 $". That's why I need the third step, to make sure it isn't placed between two numbers. But I see your point, I should have made it more clear. Commented Nov 9, 2012 at 11:58

1 Answer 1

2

You can probably sum all this into a regular expression:

echo preg_replace('/\$\s*(\d+)(?=\s*[^$])/', '$1\$', $text);

This is just a quick off-the-cuff example, matching a $ maybe followed by some whitespace followed by a number maybe followed by some whitespace and not another $, and replaces it with [number] $.

I'd recommend you learn some regular expressions.

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

Comments

Your Answer

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