PHP Regex find text between custom added HTML Tags
I have he following scenario:
Got an HTML template file that will be used for mailing
.
Here is a reduced example:
<table>
<tr>
<td>Heading 1</td>
<td>heading 2</td>
</tr>
<PRODUCT_LIST>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
</PRODUCT_LIST>
</table>
All I need to do is to get the HTML开发者_JS百科 code inside <PRODUCT_LIST>
and then repeat that code as many times as products I have on an array.
What would be the right PHP Regex code for getting/replacing this List?
Thanks!
Assuming <PRODUCT_LIST>
tags will never be nested
preg_match_all('/<PRODUCT_LIST>(.*?)<\/PRODUCT_LIST>/s', $html, $matches);
//HTML array in $matches[1]
print_r($matches[1]);
Use Simple HTML DOM Parser. It's easy to understand and use .
$html = str_get_html($content);
$el = $html->find('PRODUCT_LIST', 0);
$innertext = $el->innertext;
Use this function. It will return all found values as an array.
<?php
function get_all_string_between($string, $start, $end)
{
$result = array();
$string = " ".$string;
$offset = 0;
while(true)
{
$ini = strpos($string,$start,$offset);
if ($ini == 0)
break;
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
$result[] = substr($string,$ini,$len);
$offset = $ini+$len;
}
return $result;
}
$result = get_all_string_between($input_string, '<PRODUCT_LIST>', '</PRODUCT_LIST>');
as above is ok but with performance is really horrible If You can use PHP 5 you can use DOM object like this :
<?php
function getTextBetweenTags($tag, $html, $strict=0)
{
/*** a new dom object ***/
$dom = new domDocument;
/*** load the html into the object ***/
if($strict==1)
{
$dom->loadXML($html);
}
else
{
$dom->loadHTML($html);
}
/*** discard white space ***/
$dom->preserveWhiteSpace = false;
/*** the tag by its tag name ***/
$content = $dom->getElementsByTagname($tag);
/*** the array to return ***/
$out = array();
foreach ($content as $item)
{
/*** add node value to the out array ***/
$out[] = $item->nodeValue;
}
/*** return the results ***/
return $out;
}
?>
and after adding this function You can just use it as:
$content = getTextBetweenTags('PRODUCT_LIST', $your_html);
foreach( $content as $item )
{
echo $item.'<br />';
}
?>
yep, i just learn this today. dont use preg for html with php5
try this regular expression
in preg match all function
<PRODUCT_LIST>(.*?)<\/PRODUCT_LIST>
精彩评论