dongyinju5977
2017-07-07 16:28
浏览 20
已采纳

删除字符串中的第一个html标记

i have this text

<?php
   $example1 = '<b class="counter">1</b> This is a computer';
   $example2 = '<b class="counter">5</b> i have a laptop';
   $example3 = '<b class="counter">1</b> i need a smartphone';
   $example4 = 'i need a car'; // does not have <b> tag
?>

i'm looking for a php function to remove a part of the string, starting from <b> to </b>, so the results should be like :

$example1_result = 'This is a computer';
$example2_result = 'i have a laptop';
$example3_result = 'i need a smartphone';
$example4_result = 'i need a car';
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dongzhaiqiang6108 2017-07-07 16:47
    已采纳

    Make sure to escape from your "counter" otherwise it will not work, but the others have already answered your question with a better version using regular expressions.

    <?php
    $example1 = "<b class=\"counter\">1</b> This is a computer";
    $example2 = "<b class=\"counter\">5</b> i have a laptop";
    $example3 = "<b class=\"counter\">1</b> i need a smartphone";
    
    echo strip_tags($example1); //Outputs: 1 This is a computer
    
    $example1 = trim(substr(strstr($example1, '</b>'), strlen('</b>')));
    echo $example1; //Outputs: This is a computer
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongliaojing0554 2017-07-07 16:30

    You'll want to use strip_tags http://php.net/manual/en/function.strip-tags.php

    it essentially strips, well tags from the string:

    <?php
        $htmlStr = '<p>Text</p>';
        $str     = strip_tags($htmlStr);
    
        var_dump($str); //will echo Text
    
    评论
    解决 无用
    打赏 举报
  • douhuang2282 2017-07-07 16:33

    If you need the result after you can use substr($example, strpos($example, '</b>')) where $example is <b class="counter">1</b> This is a computer

    评论
    解决 无用
    打赏 举报
  • drzdu44226 2017-07-07 16:33
    preg_replace("(<([a-z]+)>.*?</\\1>)is","",$example1);
    

    use this as you want to remove the content inside the <b> tags also strip_tags() will keep the content inside the html tags

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题