HTML标记上的PHP preg_match()
我正在尝试使用preg_match()检索到 我写过:HTML标记上的PHP preg_match(),php,html,preg-match,Php,Html,Preg Match,我正在尝试使用preg_match()检索到 我写过: <?php $file=file_get_contents('Temp.txt'); $regexp='<div class\=\"cropped-image\" style\=\"width:102px;height:102px;\">(.*) </div>'; preg_match($regexp,$file,$string1); echo $string1[0]; ?> 输入: <t
<?php
$file=file_get_contents('Temp.txt');
$regexp='<div class\=\"cropped-image\" style\=\"width:102px;height:102px;\">(.*)
</div>';
preg_match($regexp,$file,$string1);
echo $string1[0];
?>
输入:
<table class="search-results" data-search-total="5068" data-search-type="artists" data-search-term="taylor" data-search-genre="all">
<tr class="search-result artist">
<td>
<div class="image">
<div class="thumbnail sm artist">
<a href="/artist/taylor-swift-mn0000472102" data-tooltip="{"id":"MN0000472102","thumbnail":true,"position":{"my":"left center","at":"middle right"}}">
<div class="cropped-image" style="width:102px;height:102px;" ><img src="http://cps-static.rovicorp.com/3/JPG_170/MI0003/436/MI0003436897.jpg?partner=allrovi.com" style="left:-25px" width="153" height="102" alt="Taylor Swift" data-debug="170x113 (63)"></div> </a>
</div>
</div>
<div class="right-of-image">
<div class="type">
<span class="sprite2 icon-search-artist-new" title="artist"></span>
</div>
<div class="name">
<a href="http://www.allmusic.com/artist/taylor-swift-mn0000472102" data-tooltip="{"id":"MN0000472102","thumbnail":true,"position":{"my":"left center","at":"middle right"}}">Taylor Swift</a> </div>
<div class="info">
Country, Pop/Rock
<br/>
2000s - 2010s
</div>
</div>
</td>
乡村音乐、流行音乐/摇滚音乐
2000年代至2010年代
我得到的错误是:警告:preg_match():第4行TrialHP.php中的未知修饰符“(”。我在特殊字符之前也包含了\个字符
我尝试了,它运行成功。但我必须使用regex进行赋值。我应该如何继续???您需要一个分隔符,例如
#
尝试:
$regexp='#(.*)#';
试试这个。刚刚测试过,它似乎可以工作:
<?php
$file=file_get_contents('test.txt');
$regexp='/\<div class\=\"cropped-image\" style\=\"width:102px;height:102px;\" \>(.*?)\<\/div\>/';
preg_match($regexp,$file,$string1);
//print_r($string1);
//echo "<hr />\n\n";
echo $string1[1];
?>
那个作业是错误的。你应该使用DOM解析HTML。HTML不是常规文本!@Parahatemelayev作业的目的大概是学习regexps,而不是解析DOMs。@Barmar然后你有东西要教你的老师:)@kjetilh不是我的老师。我不知道,这不是重点:)是的,试过了。我在TrialPp.php的第5行收到通知:未定义的偏移量:0错误。从输出中删除[],我收到通知:数组到字符串转换错误。因为它与任何内容都不匹配并且$string1=Array()
。我更新了我的答案。我的电脑现在可以用了。谢谢。但是你能告诉我为什么字符串[0]会抛出错误吗??数组索引不是从0开始的吗?抱歉,忘记添加我收到的通知:未定义的偏移量:0使用string1[0]时出错我不太确定。可能它没有向$string1
返回任何内容。是的,数组是基于0的,但是请记住,使用preg_match$string1[0]将返回完全匹配的模式(因此它将包括和所有内容),并且[1]将返回第一个匹配的子模式(.*)。如果在我的代码中用print\r取消注释该行,运行它并查看源代码,您可以看到数组的内容。当我在答案中尝试代码时,$string1[0]
可以正常工作。是的,但查看源代码。它将包括。[0]是完全匹配
<?php
$file=file_get_contents('test.txt');
$regexp='/\<div class\=\"cropped-image\" style\=\"width:102px;height:102px;\" \>(.*?)\<\/div\>/';
preg_match($regexp,$file,$string1);
//print_r($string1);
//echo "<hr />\n\n";
echo $string1[1];
?>