简体   繁体   中英

PHP find character by pattern in string and replace it

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?

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 .

$str = preg_replace('/(?<=\d)\@/', '%', $str);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM