[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1364
  • Last Modified:

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
0
jackjohnson44
Asked:
jackjohnson44
  • 8
  • 7
  • 5
  • +4
1 Solution
 
srikanthmadishettiCommented:
<?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
0
 
BogoJokerCommented:
$str = preg_replace("/[^\\]'/", "\'", $str);

Enjoy.
Joe P
0
 
dr_dedoCommented:
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
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ps15Commented:
Try:

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

dr_dedo: negative zero-width assertion it is :D (I love that stuff)
0
 
BogoJokerCommented:
Excuse me!?
I just tested mine and it worked.  Let me test it in php script.  Maybe I copied it wrong
0
 
BogoJokerCommented:
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;

?>
0
 
jackjohnson44Author Commented:
thanks for all your input

bogo, can you please explain what you did?

Thanks
0
 
ps15Commented:
BogoJoker:
Of course it works _NOW_, as you fixed it..

$str = preg_replace("/[^\\]'/", "\'", $str);
(this, your first post is wrong.)

$str = preg_replace('/([^\\\])\'/', "\$1\'", $str);
(this, your second post, works fine.)


$x = preg_replace("/(?<!\\\\)'/","\\'",$x);
(my fisrt post, works good too.)
0
 
dr_dedoCommented:
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
0
 
ps15Commented:
yaya, agreed =)
got the feeling he was pretending his first solution was right, pretending he didn't make an error.
sorry, again...
0
 
Richard QuadlingSenior Software DeverloperCommented:
<?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";
?>
0
 
Richard QuadlingSenior Software DeverloperCommented:
"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.



0
 
ps15Commented:
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 ;)
0
 
Richard QuadlingSenior Software DeverloperCommented:
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.
0
 
BogoJokerCommented:
Hehe, intresting method RQuadling and nice improvement ps15.
That is a pretty neat concept.  I hope I can use it some day. =)
0
 
jackjohnson44Author Commented:
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?

0
 
ps15Commented:
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 ;)
0
 
Richard QuadlingSenior Software DeverloperCommented:
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.

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

$string = preg_replace("/(?<!\\\\)(([\\\\]{2})*)'/","$1\\\\'",$string);
0
 
Richard QuadlingSenior Software DeverloperCommented:
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.


0
 
ps15Commented:
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 ( "####", "", "\\'", "\\\\" );
0
 
Richard QuadlingSenior Software DeverloperCommented:
Oops! Oh yeah. Useless ain't I
0
 
stuartc1Commented:
Why not just do this:

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

echo addslashes(stripslashes($a));
?>
0
 
BogoJokerCommented:
stuart, I think that would add slashes to more then just single quotes.
0
 
jackjohnson44Author Commented:
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?


0
 
Richard QuadlingSenior Software DeverloperCommented:
Don't do ANYTHING to the string if it is in a cookie. Leave it alone.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 8
  • 7
  • 5
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now