简体   繁体   English

str_replace无法正常工作

[英]str_replace not working properly

I was experimenting with str_replace but I'm having some problems with this specific line: 我正在尝试使用str_replace,但是此特定行存在一些问题:

$content = str_replace('<div id='demo'><a href='https://www.example.com' target='_blank'><img alt='Demo' src='//example.com/image.png' /></a></div>', '', $content);

I've tried changing the quotes but nothing worked. 我试图更改报价,但没有任何效果。 Thank you for your time. 感谢您的时间。

EDIT: I got it to work by separing the code into two different str_replace. 编辑:我通过将代码分成两个不同的str_replace使其工作。

遇到字符串时,请尝试使用单引号和双引号

$content = str_replace('<div id="demo"><a href="https://www.example.com" target="_blank"><img alt="Demo" src="//example.com/image.png" /></a></div>', '', $content);

您需要转义单引号,或使用双引号,如下所示:

$content = str_replace("<div id='demo'><a href='https://www.example.com' target='_blank'><img alt='Demo' src='//example.com/image.png' /></a></div>", '', $content)

You must escape all single quotes, like this: 您必须转义所有单引号,如下所示:

    $content = str_replace(
        '<div id=\'demo\'><a href=\'https://www.example.com\' target=\'_blank\'><img alt=\'Demo\' src=\'//example.com/image.png\' /></a></div>', '', $content
    );

First you should define the variable $content at your code 首先,您应该在代码中定义变量$ content

  $content = str_replace('<div id='demo'><a href='https://www.example.com' target='_blank'><img alt='Demo' src='//example.com/image.png' /></a></div>', '', $content);

$content will refer to what? $ content将指什么?

I will give you this suggestion : 我会给你这个建议:

 <?php

 $string='<div id="demo"><a href="https://www.example.com" target="_blank"><img alt="Demo" src="//example.com/image.png" /></a></div>something';
 $removed='<div id="demo"><a href="https://www.example.com" target="_blank"><img alt="Demo" src="//example.com/image.png" /></a></div>';

 $content = str_replace($removed , '', $string);


 echo $content;// output something
 ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM