get everything between <tag> and </tag> with php

2022-08-30 13:16:17

I'm trying to grab a string within a string using regex.

I've looked and looked but I can't seem to get any of the examples I have to work.

I need to grab the html tags <code> and </code> and everything in between them.

Then I need to pull the matched string from the parent string, do operations on both,

then put the matched string back into the parent string.

Here's my code:

$content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. &lt;code>Donec sed erat vel diam ultricies commodo. Nunc venenatis tellus eu quam suscipit quis fermentum dolor vehicula.&lt;/code>"
$regex='';
$code = preg_match($regex, $text, $matches);

I've already tried these without success:

$regex = "/<code\s*(.*)\>(.*)<\/code>/";
$regex = "/<code>(.*)<\/code>/";

答案 1

You can use the following:

$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
  • \b ensures that a typo (like ) is not captured.<codeS>
  • The first pattern captures the content of a tag with attributes (eg a class).[^>]*
  • Finally, the flag capture content with newlines.s

See the result here : http://lumadis.be/regex/test_regex.php?id=1081


答案 2

this function worked for me

<?php

function everything_in_tags($string, $tagname)
{
    $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

?>

推荐