PHP/regex: How to get the string value of HTML tag?

前端 未结 8 2035
忘了有多久
忘了有多久 2020-11-28 07:24

I need help on regex or preg_match because I am not that experienced yet with regards to those so here is my problem.

I need to get the value \"get me\" but I think

相关标签:
8条回答
  • 2020-11-28 07:54

    The following php snippets would return the text between html tags/elements.

    regex : "/tagname(.*)endtag/" will return text between tags.

    i.e.

    $regex="/[start_tag_name](.*)[/end_tag_name]/";
    $content="[start_tag_name]SOME TEXT[/end_tag_name]";
    preg_replace($regex,$content); 
    

    It will return "SOME TEXT".

    0 讨论(0)
  • 2020-11-28 07:55
    $userinput = "http://www.example.vn/";
    //$url = urlencode($userinput);
    $input = @file_get_contents($userinput) or die("Could not access file: $userinput");
    $regexp = "<tagname\s[^>]*>(.*)<\/tagname>";
    //==Example:
    //$regexp = "<div\s[^>]*>(.*)<\/div>";
    
    if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) {
        foreach($matches as $match) {
            // $match[2] = link address 
            // $match[3] = link text
        }
    }
    
    0 讨论(0)
  • 2020-11-28 08:06

    Try this

    $str = '<option value="123">abc</option>
            <option value="123">aabbcc</option>';
    
    preg_match_all("#<option.*?>([^<]+)</option>#", $str, $foo);
    
    print_r($foo[1]);
    
    0 讨论(0)
  • 2020-11-28 08:09
    <?php
    function getTextBetweenTags($string, $tagname) {
        $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
        preg_match($pattern, $string, $matches);
        return $matches[1];
    }
    
    $str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
    $txt = getTextBetweenTags($str, "font");
    echo $txt;
    ?>
    

    That should do the trick

    0 讨论(0)
  • 2020-11-28 08:11

    try $pattern = "<($tagname)\b.*?>(.*?)</\1>" and return $matches[2]

    0 讨论(0)
  • 2020-11-28 08:13

    this might be old but my answer might help someone

    You can simply use

    $str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
    echo strip_tags($str);
    

    https://www.php.net/manual/en/function.strip-tags.php

    0 讨论(0)
提交回复
热议问题