在PHP中搜索正则表达式


Search a regex in 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>

我已经写了一段代码,但它不适合我:

$string = "id'='"countdown'"";
if(strstr($contents,$string)) {
echo "found it.";
} else {
echo "not found.";
}

我希望使用一些像(.+)这样的运算符,我们可以在PERL中使用,如果我们用语法

进行字符串匹配

~/abc (+) ghi/

则abc,ghi之间的数据赋值给变量$1

与Perl相同的PHP:

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

:

if(preg_match('/abc(.+)ghi/', $var, $match) {
  print $match[1];
}

但是为了回答您最初使用regex解析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);

应该输出类似这样的内容:

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