字符串
<div id="main">
content (is INT)
<div>some more content (is not INT) other content (also INT)</div>
</div>
我需要得到一个INT型的content
。一个简单的剥离所有非整型函数将不起作用,因为other content
有时也是整型。我不能使用选择子解决方案,因为它总是在div之外,选择<div id="main">
的内容也会选择其他div。
因此,存在一种解决方案,可以从字符串开始搜索第一个<
,并在找到时删除字符串的其余部分。
(结构不能改变)
如果这正是格式,您可以使用substr和strpos就像
$html = '<div id="main">
12345
<div>foobar6789</div>
</div>
';
$content_1 = substr($html,15,strpos($html,'<div>')-15); //the first INT content
$subdiv = str_replace("</div>","",substr($html,strpos($html,'<div>')+5));
preg_match('/(?P<noint>[^0-9]+)(?P<digit>'d+)/', $subdiv, $matches);
echo $matches['noint'];//the NO INT content
echo $matches['digit'];//the second INT
使用regexp解析HTML不是一个好主意…但也许你可以只使用preg_match
…
祝你好运!