Link to home
Start Free TrialLog in
Avatar of jackjohnson44
jackjohnson44

asked on

php string replace

I would like to replace single quotes with a backslash, single quote.

If there is already a backslash single quote, I don't want to touch it.

I am not sure if a given string would have both, so I want to be able to handle both cases.

so

my mixed\'string string'has double quotes

would be
my mixed\'string string\'has double quotes

Thanks
Avatar of SRIKANTH MADISHETTI
SRIKANTH MADISHETTI
Flag of India image

<?php
$search = "geese";
$replace = "gooses";
$subject = "The geese fly away happily!";
echo "Before the replace: $subject<br />";//
Replaces geese with gooses inside of the $subject var
$subject = str_replace($search, $replace, $subject);
echo "After the replace: $subject";
?>

i think this example will help u out
Avatar of BogoJoker
BogoJoker

$str = preg_replace("/[^\\]'/", "\'", $str);

Enjoy.
Joe P
try this nasty one till i come up with a nice regex :)

$str = str_replace("_-_-","\'", str_replace("'","\'",str_replace("\'","_-_-",$str)));

"_-_-" is just a text that is unique
Try:

$x = preg_replace("/(?<!\\\\)'/","\\'",$x);
wow, it is a busy question, everyone is answering in the same time, lucky you jackjohnson44
Bogojoker: yours replaces the previous char to !

dr_dedo: negative zero-width assertion it is :D (I love that stuff)
Excuse me!?
I just tested mine and it worked.  Let me test it in php script.  Maybe I copied it wrong
This is the direct php test:
<?php

$str = "my mixed\'str'in\'g st'ring'has double quotes";
print "$str<br>";
$str = preg_replace('/([^\\\])\'/', "\$1\'", $str);
print $str;

?>
Avatar of jackjohnson44

ASKER

thanks for all your input

bogo, can you please explain what you did?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of ps15
ps15

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ps15, this is not a fighting arena regarding who is better, simply by comparing overall score, everyone will know who is better. having a typo in BogoJoker's syntax doesn't mean you won tha battle or he lost it, simple there ain't any battle !!

nevertheless, this leaves me as the first to come up with a working solution, yahooooooooooooooo :P

(just kidding)

:D
yaya, agreed =)
got the feeling he was pretending his first solution was right, pretending he didn't make an error.
sorry, again...
<?php
define ('UNIQUE_CONSTANT', '#####'); // This has to be TRULY unique for all your text.
$s_string = "my mixed\'string string'has double quotes";


$a_search_for = array
      (
      "\'",            // First HIDE the \'
      "'",             // Next look for '
      UNIQUE_CONSTANT, // Restore the \'
      );

$a_replace_with = array
      (
      UNIQUE_CONSTANT,
      "\'",
      "\'",
      );

$s_new_string = str_replace($a_search_for, $a_replace_with, $s_string);

echo "Original string = >>>$s_string<<<\nNew string = >>>$s_new_string<<<\n";
?>

results in ...

Original string = >>>my mixed\'string string'has double quotes<<<
New string = >>>my mixed\'string string\'has double quotes<<<

I know this is the same mechanism as dr_dedo, but it is a LOT easier to use.

Basically you hide away all the things you want to keep and then restore them afterwards.

The str_replace() function processes the arrays in sequence.

For this example it is like ...

<?php
$s_new_string = str_replace("\'", UNIQUE_CONSTANT, $s_string);
$s_new_string = str_replace("'", "\'", $s_new_string);
$s_new_string = str_replace(UNIQUE_CONSTANT, "\'", $s_new_string);

echo "Original string = >>>$s_string<<<\nNew string = >>>$s_new_string<<<\n";
?>
"I know this is the same mechanism as dr_dedo, but it is a LOT easier to use."

The method, not my example, is easier.

Sometimes a regex is JUST too complicated. Not for this though.

If you know your regex, then the regex method is a nice 1 liner.

The array usage of str_replace is a little more wordy, but I think significantly easier to expand.



RQuadling:

why not just:

$a_search_for = array
     (
     "\\'",            // First turn  \' into regular '
     "'"             // Next look for ''
     );
$a_replace_with = array ("'", "\\'");

Seems to make more sense to me, only 2 replace thingys, or have I overlooked something ?

Still, I like the regexes best ;)
Doh. Of course. I actually cobbled a script I have which is a LOT more complicated than this.

I have a function which takes a document (maybe 300K in size) and hides certain parts from the document before processing. These parts must NEVER be changed.

The function also replaces other parts.

Sometimes the changes make them look like the hidden parts.

It is a complicated EDI file.

But, the principle of changing the 2 parts like you've done is fine.

If you like the regex method then great. And for this request there is nothing wrong with it. Maybe I'd have suggested that first. My suggestion is just another way of doing the same thing.

What I am glad to see is no one saying you have to read every character in the string and see if it is a ' and then step back and see if it is a \ and ...

Old style BASIC character manipulation.
Hehe, intresting method RQuadling and nice improvement ps15.
That is a pretty neat concept.  I hope I can use it some day. =)
Thanks for all of your input, I wish they would let me give more than 500pts.

I am really confused now.

Can someone tell me what the best/easiest way to accomplish this is?

note that this all dosen't work if you can escape a Backslash e.g.
\\' would need to be translated to \\\' since the backslash isn't escaping the ' but the other backslash ...

A possible solution that does all that is:

$string = preg_replace("/(?<!\\\\)(([\\\\]{2})*)'/g","$1\\\\'",$string);

regexe's aren't the fastest available solution, the string_replace code is probably the fastest, but this will defenetly work, and allows you do do cool stuff in one line ;)
If you understand and use regular expressions, then the regexp mechanism is the most succinct. MAYBE a slight performance hit due to the complexities of regexp. MAYBE.

If you want a non regexp then the ps15 improvement on my code is just as good.

sorry, accidently added the 'g', it should be:

$string = preg_replace("/(?<!\\\\)(([\\\\]{2})*)'/","$1\\\\'",$string);
Now. Even though I'm a ZCE and my regexp experience is pretty good, trying to decide INSTANTLY and EXACTLY what that code is doing is little awkward.

To solve that my way I would ...

$as_search_for = array ( "\\",  "\'",  "'", "####" );
$as_replace_with = array ( "####", "", "\'", "\\" );

We have to preserve \\ and NOT get them confused with \'. So hide the \\ with #### first.

etc. etc.


RQuadling:
Looks good except you need to escape the backsoulashes in double quotes, so if you do "\'" and "'" you would acctually be refering to the same thing. you want:

$as_search_for = array ( "\\\\",  "\\'",  "'", "####" );
$as_replace_with = array ( "####", "", "\\'", "\\\\" );
Oops! Oh yeah. Useless ain't I
Why not just do this:

<?
$a = "string with 'quote \' etc";

echo addslashes(stripslashes($a));
?>
stuart, I think that would add slashes to more then just single quotes.
The problem that I am having is adding the form input into a cookie.
For some reason, if I do various things to the page, I end up with someting like

my string\\\\\\\\\\'s messed up

If there is a \' someone puts someplace, I really don't care if it gets turned into a straight '.

Performance could be an issue.

How about this approach, replace all single quotes with a backslash single quote, then change all multiple backslash quotes with a single backslash.

so
my string\\\\\\\\\\'s messed up and a single'quote

(even if that is what they put in would turn into)
my string\'s messed up and a single\'quote

is there an easy way to do this?

I am pretty sure with magic quotes turned on, adding a ' to a cookie, then rewriting the cookie each time the page loads would create a multiple backslash scenario.  how do people currently do this?


Don't do ANYTHING to the string if it is in a cookie. Leave it alone.