1

I am trying to call str_replace method in PHP.

I wanna replace \" with " but I am having issues doing that. I think PHP interprets " wrong. Is there a chance to avoid that.

$data = str_replace('\"','"',trim(ob_get_contents()));

Edit:

This is a extract of the content I am editing:

<div class=\"container-fluid\">

I would like to get

<div class="container-fluid">

Edit 2:

I tested removing \n. Interesting it only worked when using "" not ''

$data = str_replace("\n","",$test_str); // working
$data = str_replace("\n","",$test_str); // NOT working
davidev
  • 7,694
  • 5
  • 21
  • 56

2 Answers2

2
$str = '<div class=\"container-fluid\">';
$data = str_replace('\"', '"', trim($str));
var_dump($data); // <div class="container-fluid">

In PHP a string can be defined by single quotes ' and double quotes ". The difference between them is that double quotes are strings parsing mode, which means, they can parse variables and special chars inside them. While using single quotes they treat them as a pure string as they come. You can read more about them in this answer: https://stackoverflow.com/a/3446286/3454593

Chemaclass
  • 1,933
  • 19
  • 24
1

Try this

Option 1:

$str = '<div class=\"container-fluid\">';
echo stripslashes($str);

Demo link

Option 2:

$str = '<div class=\"container-fluid\">';
echo str_replace("\\", "", $str);

Demo link

Vinay Patil
  • 736
  • 6
  • 19
  • Thank you. Now it's working for me but only if I echo it. If I reference it to a new variable, it is not working. Any idea? – davidev Nov 20 '19 at 10:05
  • If the string even in your question is a part of the content then it should work. What are you getting as output same content as input? – Vinay Patil Nov 20 '19 at 10:09
  • You are right. I echo it, and it worked. Saving it on a new variable aswell. I saved it afterwards in an array and then output the array. As the array uses "" it created the \" again – davidev Nov 20 '19 at 10:12
  • If you are saving that `HTML` output in an array then it will be converted to a string again which will result PHP will add slashes again to a string. My suggestion is to replace the slashes at the time of displaying HTML on page. – Vinay Patil Nov 20 '19 at 10:15
  • @VinayPatil Yeah that's what I am doing. I would like to get the output directly ready. The one getting the output shouldn't need to parse or edit it anymore. Any chance to add this to an array without the escape \? – davidev Nov 20 '19 at 10:29
  • Can you update the array code also in the question? as per your last comment question in incomplete to provide the desired output – Vinay Patil Nov 20 '19 at 10:34
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202708/discussion-between-davidev-and-vinay-patil). – davidev Nov 20 '19 at 10:47