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. <code>Donec sed erat vel diam ultricies commodo. Nunc venenatis tellus eu quam suscipit quis fermentum dolor vehicula.</code>" $regex=''; $code = preg_match($regex, $text, $matches);
I've already tried these without success:
$regex = "/<code\s*(.*)\>(.*)<\/code>/"; $regex = "/<code>(.*)<\/code>/";
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.
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.
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" .
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.
You can use the following:
$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
\b
ensures that a typo (like <codeS>
) is not captured.[^>]*
captures the content of a tag with attributes (eg a class).s
capture content with newlines.See the result here : http://lumadis.be/regex/test_regex.php?id=1081
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]; } ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With