2012-08-09 17 views
0

我想要做的事,如:如何从给定的HTML标记中提取特定的子字符串,但不知道其长度?

<?php 
$text = "<font style='color: #fff'>"; 
$replaceandshow = str_replace("<font style=\"?\">", "the font style is ?", $text); 
echo $replaceandshow; 
?> 

例如,?是颜色:#fff,但我希望PHP能够自己追踪它,是否可能+如果可能的话,我该怎么做?

P.S:有人给了我一个代码,但它现在正在工作,它为我显示一个白页。

<?php 
$colorstring = "<font style='#fff'>"; 
$searchcolor = preg_replace('[a-fA-F0-9]{3,6}','[font style=$1]Test[/font]',$colorstring); 
echo $searchcolor; 

感谢您的帮助。

回答

1

因为错误报告被关闭你越来越白页。您的代码中的错误在preg_replace中缺少分隔符。此外,为了使用反向引用,您应该将括号中所需的表达式括起来。

preg_replace('/([a-fA-F0-9]{3,6})/','the font style is $1',$colorstring); 

应给出正确的输出。

您可能会考虑使用更紧缩的表达式,因为当前表达式对匹配其他字符串(如“FFFont”)非常开放。另外需要注意的是表达式可能会导致输出。

<font style='color: the color is #fff'> 

尝试:

/<font style='color: #([a-fA-F0-9]{3,6})'>/ 
+0

非常感谢。 – 2012-08-09 18:26:21

0

这将简单style属性工作:

$text = "<font style='color: #fff'>"; 
preg_match("/<font style=['\"]([^'\"]+)['\"]>/", $text, $matches); 
echo "The font style is ".$matches[1]; 

对于任何更复杂(例如:如果它包含引号),你需要使用一个HTML解析器,如http://www.php.net/manual/en/class.domdocument.php

1

由于你需要从任何HTML中抽取基本的任何属性,你可以使用php XML解析来做到这一点。

<?php 
$doc=new DOMDocument(); 
$doc->loadHTML("<html><body>Test<br><font style='color: #fff;'>hellow</font><a href='www.somesite.com' title='some title'>some site</a></body></html>"); 
$xml=simplexml_import_dom($doc); // just to make xpath more simple 
$fonts=$xml->xpath('//font'); 
foreach ($fonts as $font) { 
    echo 'font style = '.$font['style']."<br />"; 
} 

$as=$xml->xpath('//a'); 
foreach ($as as $a) { 
    echo 'href = '.$a['href'] . ' title = ' . $a['title']."<br />"; 
} 
?> 

,将返回:

font style = color: #fff; 
href = www.somesite.com title = some title 

您可以使用不同的foreach循环你需要提取,然后任何你想要的属性输出的每个HTML标记。

回答基于How to extract img src, title and alt from html using php?

+0

@ Aviv.A看到新的答案,您可以从任何HTML获取任何属性。 – tsdexter 2012-08-09 18:43:53

相关问题