Django Johnson
Django Johnson

Reputation: 1449

Replace only certain '%' in a string

I am using str_replace() to replace all the slashes in a string with '%' and then I run the newly edited string through a function. One of the things this function does is adds '%%%' to the string.

Now, I need to replace only the percentage signs that I replaced before, that were slashes before, with slashes again.

So if the original string looks like this: 'the/wuick/bornw/foc/jumps/over/the/lazy/dog.'

After passing it through the function it will look like this: 'The%quick%brown%fox%jumps%over%the/lazy%dog.%%%'

And then after putting it through the part I need help with, it will look like this: 'The/quick/brown/fox/jumps/over/the/lazy/dog.%%%'

I would greatly appreciate any and all help replacing only the % that I had done with str_replace() before.

Upvotes: 1

Views: 198

Answers (3)

Eduardo Ponce de Leon
Eduardo Ponce de Leon

Reputation: 9706

without too many complications execute in this order:

$str = 'The%quick%brown%fox%jumps%over%the/lazy%dog.%%%';
$str= str_replace('%%%','***triple_percent**', $str);
$str= str_replace('%','/', $str);
$str= str_replace('***triple_percent**','%%%', $str);

Idealy first see why you have so many %, I am sure you can simplify your functions.

Another solution is using regular expressions like Tim says in his answer

$str= preg_replace('/(?<!%)%(?!%)/', '/', $str);

Break apart means:

(?<!%)     Not % before
%          find %
(?!%)      Not % after

also add g so it can find it many times, and i for case sensitive in the case that you might need it:

$str= preg_replace('/(?<!%)%(?!%)/ig', '/', $str);

Upvotes: 0

Diego Tolentino
Diego Tolentino

Reputation: 29

Add another replate with blank string like:

$string = str_replace('%', '', $string);

Upvotes: -1

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

To replace single % signs with slashes, you can use

$result = preg_replace('/(?<!%)%(?!%)/', '/', $subject);

This uses negative lookaround assertions to make sure only those % signs are matched that are neither preceded nor followed by another % sign.

See it on regex101.com.

Upvotes: 4

Related Questions