开发者

php preg_match problem

how can i get 41P86246HOH7C1G4A983321910HDL63U9 from the following wit开发者_如何学Pythonh preg_match

input type="text" value="41P86246HOH7C1G4A983321910HDL63U9" id=""


DOMDocument::loadHTML("<$input>")->getElementsByTagName('input')
    ->item(0)->getAttribute('value');


What about something like this :

$str = 'input type="text" value="41P86246HOH7C1G4A983321910HDL63U9" id=""';
$m = array();
if (preg_match('#value="([^"]+)"#', $str, $m)) {
    var_dump($m[1]);
}

Which will match everything between the double quotes that come with value, and get you :

string '41P86246HOH7C1G4A983321910HDL63U9' (length=33)


But, as a sidenote : if you are trying to "parse" HTML with regex, it's generally not the "best" way ; HTML is not quite regular enough for regex...


Simply, without extra characters:

preg_match('/(?<=value=")[0-9A-Za-z]+/', $str, $match);

Your result is in $match[0];


With something like this:

if(preg_match('@value="([^"]*)"@', $text, $m)){
    echo $m[1];
}

But you can also make something who split the string in each key with this value.

function attributes($text){
    $attrs = array();

    if(preg_match_all('@(\b[^=]*\b)\s*=\s*"([^"]+)"@', $text, $matches, PREG_SET_ORDER)){
        foreach($matches as $m){
            $attrs[$m[1]] = $m[2];
        }
     }

     return $attrs;
 }

 // Use like this
 $attrs = attributes('input value="bla"');
 if(isset($attrs['value'])){
     echo $attrs['value'];
 }


don't even have to use regex. Just use PHP's string methods

$str='input type="text" value="41P86246HOH7C1G4A983321910HDL63U9" id=""';
$s = explode(" ",$str);
// go through each element, find "value"
foreach($s as $a=>$b){
    if(strpos($b,"value")!==FALSE){
        $find = explode("=",$b);
        print $find[1];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜