Replace only certain '%' in a string - php

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.

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.

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

Add another replate with blank string like:
$string = str_replace('%', '', $string);

Related

Preg Replace with Spaces but only single space

Okay so consider the following string:
"Hello How are you??"
I'd like it to return:
"Hello_How_are_you"
But my preg_replace is this:
preg_replace("/[^A-Za-z0-9]/","_",$string);
Which returns the following:
"Hello____How are you"
Whilst good, it gets rid of the foreign characaters but leaves a long line of ___ which looks ugly. I understand why, because it is replacing the spaces with _ which I what I asked it to do. However i'd like to to only output the one _ where it's replaced things.
How can I achiieve this, is it done in the regex or some other way?
Just add a quantifier: +. + means at least one of what was before, grab as many possible:
preg_replace("/[^A-Za-z0-9]+/","_",$string);
This can be an alternative regex.
$str = "Hello How are you??";
$op = preg_replace("/\s+/", "_", $str); // suggested by #Toto
//(or)
$op = preg_replace("/[\s]{1,}/", "_", $str);

PHP preg_replace pattern only seems to work if its wrong?

I have a string that looks like this
../Clean_Smarty_Projekt/tpl/templates_c\.
../Clean_Smarty_Projekt/tpl/templates_c\..
I want to replace ../, \. and \.. with a regulare expression.
Before, I did this like this:
$result = str_replace(array("../","\..","\."),"",$str);
And there it (pattern) has to be in this order because changing it makes the output a little buggy. So I decided to use a regular expression.
Now I came up with this pattern
$result = preg_replace('/(\.\.\/)|(\\[\.]{1,2})/',"",$str);
What actually returns only empty strings...
Reason: (\\[\.]{1,2})
In Regex101 its all ok. (Took me a couple of minutes to realize that I don't need the /g in preg_replace)
If I use this pattern in preg_replace I have to do (\\\\[\.]{1,2}) to get it to work. But that's obviously wrong because im not searching for two slashes.
Of course I know the escaping rulse (escaping slashes).
Why doesn't this match correctly ?
I suggest you to use a different php delimiter. Within the / delimiter, you need to use three \\\ or four \\\\ backslashes to match a single backslash.
$string = '../Clean_Smarty_Projekt/tpl/templates_c\.'."\n".'../Clean_Smarty_Projekt/tpl/templates_c\..';
echo preg_replace('~\.\./|\\\.{1,2}~', '', $string)
Output:
Clean_Smarty_Projekt/tpl/templates_c
Clean_Smarty_Projekt/tpl/templates_c

preg_replace on everything prior to character

I am trying to remove parts of a string which has an ID and : before it. So for example:
2846:ZE1,2847:ZE2,2848:ZE3,713:DY10,412:CF10
But I want it to look like this:
ZE1,ZE2,ZE3,DY10,CF10
I have tried the following preg_replace:
$remove = preg_replace('/[0-9]\:+/', '', $postcodes_id);
But this only removes the last digit and not all of it:
284ZE1,284ZE2,284ZE3,71DY10,41CF10
any help would be great?
A non regex solution
parse_str(str_replace(array(':',','),array('=','&'),$str1),$str1);
Demo
Try this:
$remove = preg_replace('/[0-9]+\:/', '', $postcodes_id);
Adding the + means "one or more digit" instead of your code which is "just one".
I'm pretty sure you don't need the \ before the :...
You have the + in the wrong place, it should be:
preg_replace('/[0-9]+:/', '', $postcodes_id);
You also don't need to escape :, it has no special meaning in regular expressions.

Regexp for preg_replace in PHP

I have strings like this (some examples):
F7998FM3213/02F
J442554NM/05
K439459845/34D
I need to use PHP with preg_replace and regular expressions to delete all non-numeric characters in any string, after the forward-slash, '/'.
For example the codes above would look like this afterwards:
F7998FM3213/02
J442554NM/05
K439459845/34
If you're going for readability, something like this would be perfect:
$parts = explode("/",$line,2);
$parts[1] = preg_replace("/\D/","",$parts[1]);
$output = implode("/",$parts);
However, for conciseness and based entirely on the examples you have given, try this:
$output = preg_replace("/\D+$/","",$input);
This will strip any non-numeric characters from the end of the string, which seems to be what you're after based on your examples.
you can use this:
$subject = <<<LOD
F7998FM3213/02F
J442554NM/05
K439459845/34D
K439459845/34D34
LOD;
echo preg_replace('~^[^/]*+/\K|[^\d\n]++~m', '', $subject);
explanation:
The regex is an alternation between two things:
You match the begining until you encounter / included
the part after the / that is all that is not a digit or a new line one or more times
Since the begining of the string is checked at first, all non digit characters are removed after the /
To remove all \D anywhere after a / you could replace:
(?:/\K|\G(?!^))(\d*)\D+
with $1. Like:
preg_replace(',(?:/\K|\G(?!^))(\d*)\D+,', '$1', $str);

How do you loop through a string in php and replace '%' characters that are ONLY followed by another '%' character?

Here is what I am trying to achieve in PHP:
I have this string: host/%%%25asd%%
Now I want to loop through it and replace only the % _blank characters with %25. So I get the output as host/%25%25%25asd%25%25. (The %25 was untouched because the % wasn't followed by another %)
How should I go by doing this? regex? if so do you have an example? or loop through every character in the string and replace? I was thinking about using str_pos for this but it might after one replacement, the positions in the string would change :(
[Edit: Let me add a couple more information to ease up the confusion. %25 is just an example, it could be anything like %30 or %0a, I won't know before hand. Also the string could also be host/%%25asd%% so a simple replace for %% screw it up as host/%2525asd%25 instead of host/%25%25asd%25. What am trying to achieve is to parse a url into how google wants it for their websafe api. http://code.google.com/apis/safebrowsing/developers_guide_v2.html#Canonicalization. If you look at their weird examples.]
Use preg_replace:
$string = preg_replace('/%(?=%)/', '%25', $string);
Note the lookahead assertion. This matches every % that is followed by a % and replaces it with %25.
Result is:
host/%25%25%25asd%25%
EDIT Missed the case for the last %, see:
$string = preg_replace('/%(?=(%|$))/', '%25', $string);
So the lookahead assertion checks the next character for another % or the end of the line.
How about a simple string (non-regex) replace of '%%' by '%25%25'?
This is assuming you indeed want the output to be host/%25%25%25asd%25%25 as you mentioned and not one %25 at the end.
edit: This is another method that might work in your case:
Use the methods urlencode and urldecode, e.g.:
$string = urlencode(urldecode("host/%%%25asd%%"));
use str_replaceenter link description here instead of preg_replace , its a lot easier to apply and clean
How about something like this?
s/%(?![0-9a-f]+)/%25/ig;
$str = 'host/%%%25asd%%';
$str =~ s/ % (?![0-9a-f]+) /%25/xig;
print $str."\n";
host/%25%25%25asd%25%25

Categories