user4661379
user4661379

Reputation:

How to check and remove the additional back slash coming in account for for apostrophe in PHP?

I've a string in a variable titled $str as follows. This I got after converting it into JSON format. So the one more additional slash is added by JSON so please ignore it as it would not display while showing the string.

$str ="Let\\'s\nIt\\'s\nHe\\'s\nShe\\'s"; # \n is used for new line character, please ignore it

Now I want to check the presence of such backslash/es in a string and if they are present remove them and get the desired cleaned up string. In above case the output string should be(after converting it into JSON format) : "Let\'s\nIt\'s\nHe\'s\nShe\'s"

I tried below code but it didn't work out for me:

$str         = br2nl(str_replace('\\','',$str));
function br2nl($buff = '') {
    $buff = mb_convert_encoding($buff, 'HTML-ENTITIES', "UTF-8");
    $buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
    $buff = trim($buff);

    return $buff;
  }

Can some one please help me in this regard please?

Upvotes: 0

Views: 217

Answers (1)

Bogdan Stăncescu
Bogdan Stăncescu

Reputation: 5450

As previously suggested, stripslashes() is the best way to do this:

<?php
  $dirty ="Let\\'s\nIt\\'s\nHe\\'s\nShe\\'s";
  $clean = stripslashes($dirty);
  echo $clean."\n";
?>

Output:

Let's
It's
He's
She's

Upvotes: 1

Related Questions