如何获得找到的值,而不是替换?使用preg_replace php

时间:2015-03-03 17:27:36

标签: php web

如何获取找到的值,而不是替换?

echo $response=$htmlParserA->find("/tbody/tr/td",5)->plaintext."<br>";
$str=preg_replace("/[0-9][0-9][0-9]/","",$response);
echo $str;

响应:
在HTTP / 1.1 301永久移动之前 HTTP / 1.1永久移动后

如何获得301?

解答:

$str=preg_match("/[0-9][0-9][0-9]/",$response,$asd); 
echo $asd[0];

1 个答案:

答案 0 :(得分:2)

preg_match会做你想做的事:

$input = "HTTP/1.1 301 Moved Permanently";
$matches = array();
$found = preg_match("/\d{3}/", $input, $matches);
if($found)
{
    echo "Code = " . $matches[0];
}

如果需要,您可以使模式更严格:

$found = preg_match("/HTTP\/1\.1\s(\d{3})/", $input, $matches);
if($found)
{
    echo "Code = " . $matches[1];
}