0

Here is a string:

$str = "Discount 5.5@, Update T@";

I want to replace symbol '@' to '%' but only if it has numbers (int or dec) before:

"Discount 5.5%, Update T@"

I use:

preg_replace("/[0-9.]*@/", "%", $str);

But it just removes any number before % sign, what I do worng?

1
  • The . in [] means almost any character with some modifiers all. Its not \. Commented May 21, 2014 at 9:36

3 Answers 3

2

See my comment above. I would suggest a bit different expression:

preg_replace("/(\d+(?:\.\d+)?)(\s*)\@/", "$1$2%", $str);

This expression will match 5@, but 5.5@ as well (with or without floating point). However it will not match 5.@.

\d means numbers, equal to [0-9], the + (plus) means 1 or more, but not 0 occurrences. The second expression starting with with ?: (which means not to match as group) means to find . (dot) immediately after the first number sequence and to be followed by numbers - whole zero or one time (not to match 5.15.25@).

We then check for a spaces (0 or more times), then we turn them back after replacing with $2.

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

2 Comments

Great! How about if 5.5@ or 5.5 @ space between?
@KenTang, if you dedicate one week to test and learn regular expressions you will see it is not so hard. :)
2
$str = preg_replace('/(?<=\d)\@/', '%', $str);

Comments

0

First check the string if there are numbers in it. Than do a simple str_replace.

$str = 'Discount 5.5@, Update T@';
preg_match_all('!\d+!', $str, $matches);
if(!empty($matches)) { 
   str_replace('@','%', $str);
}

3 Comments

Why are you checking it before with preg_match_all(); and dont use preg_replace right away?
@Xatenev because of the OP's title
Well a preg_replace(); would fit. in his answer hes already using peg_replace() too

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.