在PHP中搜索正则表达式

在PHP中搜索正则表达式,php,Php,我正在尝试用PHP搜索文本字符串。为此,我使用 $filename = "http://google.com/"; $filehandle = fopen($filename, "rt"); $contents = fread($filehandle, 10000); 现在要读取span id中的数据,我们有: <span style="font-size:18px" id="countdown">4d 19h 34m 43s</span> 我希望使用一些操作符,比如

我正在尝试用PHP搜索文本字符串。为此,我使用

$filename = "http://google.com/";
$filehandle = fopen($filename, "rt");
$contents = fread($filehandle, 10000);
现在要读取span id中的数据,我们有:

<span style="font-size:18px" id="countdown">4d 19h 34m 43s</span>
我希望使用一些操作符,比如我们可以在PERL中使用的(++),如果我们让字符串与语法匹配

~/abc(+)ghi/


然后abc、ghi之间的数据被分配给变量$1。

与Perl的PHP等价物:

if($var=~/abc(.+)ghi/) {
  print $1;
}
是:


但要回答使用正则表达式解析HTML的原始问题,我建议您看看合适的HTML解析器。

就您的示例而言;您不需要避开=符号:

$string = "id=\"countdown\"";

if(strstr($contents,$string)) {
  echo "found it.";
} else {
  echo "not found.";
}
或者,您可以使用单引号:

$string = 'id="countdown"';

这应该可以解决您的strstr()调用,但我同意codaddict使用preg_match()的建议。

好的,让我们采用preg_match方法;这将在span标记之间搜索并拉出数据:

preg_match("/<span style="font-size:18px" id="countdown">(.+)<\/span>/", $contents);
preg_match(“/(.+)/”,$contents);
输出类似于以下内容的内容:

Array
(
    [0] => <span style="font-size:18px" id="countdown">4d 19h 34m 43s</span>
    [1] => 4d 19h 34m 43s
)
数组
(
[0]=>4d 19h 34m 43s
[1] =>4d 19h 34m 43s
)

首先,不要试图用正则表达式解析html,请阅读本文-其次,您的文件名是Google.com,您想做什么?下载Internet?尝试了$string=“id=\”倒计时\”;同样如此,但即使这样也会导致echo“未找到”;你能推荐一些解析器吗?
preg_match("/<span style="font-size:18px" id="countdown">(.+)<\/span>/", $contents);
Array
(
    [0] => <span style="font-size:18px" id="countdown">4d 19h 34m 43s</span>
    [1] => 4d 19h 34m 43s
)