如何打印包含preg_match中单词的行?

时间:2011-08-04 11:12:46

标签: php regex preg-match

mysql表“server_var_dump”中的一个字段,其中包含许多详细信息,包括站点访问者的USER_AGENT。现在我只需要包含行的USER_AGENT。现在我编写了以下脚本来匹配输出字符串的USER_AGENT。 现在我只需要打印那些包含USER_AGENT

的行
$result = mysql_query("SELECT server_var_dump FROM pageviews LIMIT 0,10");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    //printf("%s", $row["server_var_dump"]);
    if(preg_match("/[USER_AGENT]/", $row["server_var_dump"])){
    echo "match found.";
    }
    else
    echo "No matches found";     
}

请建议我如何打印包含USER_AGENT的行?

谢谢!

4 个答案:

答案 0 :(得分:1)

if(preg_match("/.*\[USER_AGENT\].*/"   //don't forget escape [ and ] chars as Salaman A said
    , $row["server_var_dump"],$matches)){
    //. is every char except newline char, So,you should get all string
    echo "match found.";
    //use $matches[0]
}
else
    echo "No matches found";

示例:

preg_match('/.*a.*/',"bc\nbac\nxy",$m);
print($m[0]); //prints bac

答案 1 :(得分:1)

一旦你拿到它就打印出来有什么问题?

$match_found = false;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    if(preg_match("/[USER_AGENT]/", $row["server_var_dump"])){
        echo $row["server_var_dump"];
        $match_found = true;
        break;
    }
}
if(!$match_found) {
    echo "No matches found";
}

或者,您需要获得匹配的值,如下所示:

$match_found = false;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $matches = array();
    if(preg_match("/[USER_AGENT](.+)/", $row["server_var_dump"], $matches)){
        echo $matches[1];
        $match_found = true;
    }
}
if(!$match_found) {
    echo "No matches found";
}

答案 2 :(得分:0)

o / p的ok部分是这样的:http://pastebin.com/e1qHG64Q 当我给出

$result = mysql_query("SELECT server_var_dump FROM pageviews LIMIT 0,10");
 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$found = false;
$lines = explode("\n", $row["server_var_dump"]);
// $lines = explode("\\n", $row["server_var_dump"]);
for ($x = 0; $x < count($lines); $x++) {
    if(preg_match("/[HTTP_USER_AGENT]/", $row["server_var_dump"])==TRUE)
    //if (strstr($lines[$x], "[USER_AGENT]")==TRUE)
     {
        echo $lines[$x];
        $found = true;
        break;
    }
}

它给了我o / p之类的数组数组数组 并且当按照建议给出strstr时,它给出o / p like array(array(array(array) 。使用/ n爆炸o / p可能无法正常工作..任何其他类型的黑客攻击我只能从中获取USER_AGENT行吗?

答案 3 :(得分:0)

得到了黑客! ;)

$result = mysql_query("SELECT server_var_dump FROM pageviews LIMIT 0,10");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$found = false;
$data=str_replace("=>"," ",$row["server_var_dump"]);
$lines = explode("\n", $data);

// $lines = explode("\\n", $row["server_var_dump"]);
    str_replace("\n"," ",$row["server_var_dump"]);
for ($x = 0; $x < count($lines); $x++) {
    if(preg_match("[HTTP_WAP_CONNECTION]", $lines[$x])==TRUE){
    //if (strstr($lines[$x], "[USER_AGENT]")==TRUE)
     //{
            //if(strpos($lines[$x],"[HTTP_USER_AGENT]")){
                    //echo substr($lines[$x],18);
    $y=$x-1;
    echo "$lines[$y] \n";
    }