Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

regex

php

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 my function has an error. The number of html tags are dynamic. It can contain many nested html tag like a bold tag. Also, the "get me" value is dynamic.

<?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; ?> 
like image 411
marknt15 Avatar asked May 06 '09 09:05

marknt15


People also ask

How get p value from tag in PHP?

$p = $domdoc->getElementById('categories')->getElementsByTagName('p')->item(0);

How do I match a string in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

How do you check if a string matches a regex in PHP?

Matching a string In PHP, you can use the preg_match() function to test whether a regular expression matches a specific string. Note that this function stops after the first match, so this is best suited for testing a regular expression more than extracting data.

What does Preg_match return in PHP?

The preg_match() function returns whether a match was found in a string.


2 Answers

<?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

like image 167
takete.dk Avatar answered Sep 20 '22 08:09

takete.dk


Try this

$str = '<option value="123">abc</option>         <option value="123">aabbcc</option>';  preg_match_all("#<option.*?>([^<]+)</option>#", $str, $foo);  print_r($foo[1]); 
like image 24
pkwebmarket Avatar answered Sep 24 '22 08:09

pkwebmarket