Using PHP to remove a html element from a string

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

I am having trouble working out how to do this, I have a string looks something like this...

    $text = "<p>This is some example text This is some example text This is some example text</p>              <p><em>This is some example text This is some example text This is some example text</em></p>              <p>This is some example text This is some example text This is some example text</p>";

I basically want to use something like preg_repalce and regex to remove

<em>This is some example text This is some example text This is some example text</em>

So I need to write some PHP code that will search for the opening <em> and closing </em> and delete all text in-between

hope someone can help, Thanks.

回答1:

In case if you are interested in a non-regex solution following would aswell:

<?php     $text = "<p>This is some example text This is some example text This is some example text</p>              <p><em>This is some example text This is some example text This is some example text</em></p>              <p>This is some example text This is some example text This is some example text</p>";       $emStartPos = strpos($text,"<em>");     $emEndPos = strpos($text,"</em>");      if ($emStartPos && $emEndPos) {         $emEndPos += 5; //remove <em> tag aswell         $len = $emEndPos - $emStartPos;          $text = substr_replace($text, '', $emStartPos, $len);     }  ?>

This will remove all the content in between tags.



回答2:

$text = preg_replace('/([\s\S]*)(<em>)([\s\S]*)(</em>)([\s\S]*)/', '$1$5', $text);


回答3:

$text = '<p>This is some example text This is some example text This is some example text</p> <p><em>This is the em text</em></p> <p>This is some example text This is some example text This is some example text</p>';  preg_match("#<em>(.+?)</em>#", $text, $output);  echo $output[0]; // This will output it with em style echo '<br /><br />'; echo $output[1]; // This will output only the text between the em

[ View output ]

For this example to work, I changed the <em></em> contents a little, otherwise all your text is the same and you cannot really understand if the script works.

However, if you want to get rid of the <em> and not to get the contents:

$text = '<p>This is some example text This is some example text This is some example text</p> <p><em>This is the em text</em></p> <p>This is some example text This is some example text This is some example text</p>';  echo preg_replace("/<em>(.+)<\/em>/", "", $text);

[ View output ]



回答4:

Use strrpos to find the first element and then the last element. Use substr to get the part of string. And then replace the substring with empty string from original string.



回答5:

  format: $text = str_replace('<em>','',$text); $text = str_replace('</em>','',$text);


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!