php preg_match sorun

4 Cevap

nasıl i 41P86246HOH7C1G4A983321910HDL63U9 preg_match ile aşağıdaki alabilirsiniz

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

4 Cevap

Böyle bir şey ile:

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

Ama aynı zamanda bu değerle her tuş dize bölmek şey yapabilirsiniz.

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'];
 }

Ne bu böyle bir şey:

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

value ile gelir ve seni almak çift tırnak arasındaki her şeyi maç olacak Hangi:

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...

Basitçe, ekstra karakterler olmadan:

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

Sizin sonucu $match[0] içinde;

Hatta regex kullanmak zorunda değilsiniz. Sadece PHP'nin dize yöntemleri kullanmak

$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];
    }
}