doubi2228
doubi2228
2015-05-21 22:55
浏览 52
已采纳

如何通过指定开始和结束字符从字符串中子字符串? [关闭]

I have some texts that are always begin with an image tag , so i want to print the text without the image by specifying the start and the end characters of the string that should be removed and get the rest of the text, something like:

explode($text, '<img', '/>'); // where explode($string, $start_chars, $end_chars);

for example:

$text = "<img src='anything' width='100' height='200'/><h1>Hello World!</h1>";

the output should be <h1>Hello World!</h1>

so how I can do that in php?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • douzhang8144
    douzhang8144 2015-05-22 00:02
    已采纳

    seems to be the optimal answer:

    $dom = new DOMDocument();
    $dom->loadHTML($m->en);
    $node = $dom->getElementsByTagName('img')->item(0);
    $node->parentNode->removeChild($node);
    $string = $dom->saveHTML();
    echo $string;
    
    点赞 评论
  • dqq3623
    dqq3623 2015-05-21 23:01

    You may have not heard of the substr() function of PHP. It is indicated in here!

    http://php.net/substr

    点赞 评论
  • douzhuo6931
    douzhuo6931 2015-05-21 23:15

    Revised based on new question...

    Use DOMDocument:

    $text = "<img src='anything' width='100' height='200'/><h1>Hello World!</h1>";
    $dom = new DOMDocument();
    $dom->loadHTML($text);
    $h1Tags = $dom->getElementsByTagName('h1');
    $string = $dom->saveHTML($h1Tags->item(0));
    echo $string;
    

    Output: <h1>Hello World!</h1>

    See here for more info / examples

    点赞 评论
  • dongmaomou4117
    dongmaomou4117 2015-05-21 23:33

    Given some text like:

    <img src='img1.png' width='100' height='200'/><h1>Title 1</h1>
    <img src='img2.png' width='100' height='200'/><h1>Title 2</h1>
    <img src='img4.png' width='100' height='200'/><h1>Title 3</h1>
    

    You state you want to collect just the text that would appear between the IMG tags. This was not clear upfront, and was suggested, you can use the DOMDocument to parse the HTML.

    Using Regular Expressions is another way to go. Example: https://regex101.com/r/kH0xA3/1

    $re = "/<*img.*\\/>(.*)/im"; 
    $str = "<img src='img1.png' width='100' height='200'/><h1>Title 1</h1>
    <img src='img2.png' width='100' height='200'/><h1>Title 2</h1>
    <img src='img4.png' width='100' height='200'/><h1>Title 3</h1>"; 
    
    preg_match_all($re, $str, $matches);
    
    点赞 评论
  • doucheng5209
    doucheng5209 2015-05-21 23:37

    Try with this:

    $text = "<img src='anything' width='100' height='200'/><h1>Hello World!</h1>";
    
    $dom = new DOMDocument();
    $dom->loadHTML($text);
    
    $node = $dom->getElementsByTagName('img')->item(0);
    $node->parentNode->removeChild($node);
    
    $dom->removeChild($dom->doctype);           
    $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild);
    
    echo $dom->saveHtml();
    
    点赞 评论

相关推荐