Created
November 21, 2013 18:31
-
-
Save AgelxNash/7586932 to your computer and use it in GitHub Desktop.
Вырезание текста между HTML тэгов. Корректно воспринимает любые уровни вложенности тэгов
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Вырезание текста между HTML тэгов | |
* | |
* @author Agel_Nash <Agel_Nash@xaker.ru> | |
* @version 0.1 | |
* | |
* @param string $html HTML текст | |
* @param string $tag HTML тэг в котором производить поиск | |
* @return array | |
*/ | |
function betweenTag($html, $tag = 'pre'){ | |
$replace = array(); | |
$j = 0; | |
do{ | |
$new = false; | |
//Поиск открывающего тэга (одного!) | |
preg_match('%(<'.$tag.'[^>]*>)(.*)%s', $html, $m); | |
if(isset($m[1], $m[2])){ | |
//Начинаем поиски закрывающих тегов (всех до конца документа) | |
preg_match_all('%</'.$tag.'[^>]*>%is', $m[2], $tmp, PREG_OFFSET_CAPTURE); | |
if( ! empty($tmp[0])){ | |
foreach($tmp[0] as $j=>$subTmp){ | |
$closeTag = $subTmp[0]; //закрывающий тэг | |
$subText = substr($m[2], 0, $subTmp[1]); //Тексту внутри тэгов | |
//подсчет открывающих тэгов внутри полученного текста | |
preg_match_all('%(<'.$tag.'[^>]*>)%s', $subText, $count); | |
if(count($count[0])==$j){ | |
$replace[] = array($m[1], $subText, $closeTag); | |
$new = true; | |
break; | |
} | |
} | |
$html = substr($m[2], $tmp[0][$j][1] + strlen($tmp[0][$j][0])); | |
} | |
if( ! $new){ | |
if(isset($tmp[0][$j]) && $j < $count[0]){ | |
$subTmp = $tmp[0][$j]; | |
$closeTag = $subTmp[0]; | |
$subText = substr($m[2], 0, $subTmp[1]).$closeTag; | |
$html = substr($m[2], $subTmp[1] + strlen($closeTag)); | |
$replace[] = array($m[1], $subText, $closeTag); | |
}else{ | |
$replace[] = array($m[1], $m[2], ''); | |
$html = ''; | |
} | |
} | |
}else{ | |
$html = ''; | |
} | |
}while( ! empty($html)); | |
return $replace; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment