Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get everything between <tag> and </tag> with php [duplicate]

Tags:

regex

php

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>/"; 
like image 261
Nate Avatar asked Feb 12 '12 21:02

Nate


People also ask

How to extract content between HTML tags in PHP?

preg_match() function is the easiest way to extract text between HTML tags with REGEX in PHP. If you want to get content between tags, use regular expressions with the preg_match() function in PHP. You can also extract the content inside the element based on the class name or ID.

How to get content between tags REGEX?

You can use "<pre>(. *?) </pre>" , (replacing pre with whatever text you want) and extract the first group (for more specific instructions specify a language) but this assumes the simplistic notion that you have very simple and valid HTML.

How will you get all the matching tags in a HTML file?

If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method. This example returns a list of all <p> elements with class="intro" .

What does strip_ tags do PHP?

The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped. This cannot be changed with the allow parameter. Note: This function is binary-safe.


2 Answers

You can use the following:

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

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

like image 138
piouPiouM Avatar answered Oct 03 '22 06:10

piouPiouM


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]; }  ?> 
like image 26
moni as Avatar answered Oct 03 '22 07:10

moni as