开发者

Preg_match a string, must containing Letters and numbers

The sentence maybe: BenQ G2420HDBL 23.6" Wide LCD Monitor

Need to grab the "G2420HDBL" part. The letters and numbers may be in a different order but still remains a string with both letters and n开发者_如何学Pythonumbers present.


You can use the following regex in case-insensitive mode:

(?=[a-z]*[0-9])(?=[0-9]*[a-z])[a-z0-9-]+

Basically it matches the first string that is made up of only letters and numbers with atleast one letter and atleast one number.

In PHP:

if(preg_match("/(?=[a-z]*[0-9])(?=[0-9]*[a-z])([a-z0-9-]+)/i",$input,$match)) {
   echo $match[1];
}

See it


$number = substr($name, 6, strlen($name) - 28);


You can use ctype_alnum but there is probably a better way using regexes:

$str = "BenQ G2420HDBL 23.6";
$pieces = split(' ', $str);
$theStr = '';
foreach($pieces as $piece) {
    if(ctype_alnum($piece)) {
        $theStr = $piece;
        break;
    }
}


Now I understand what you actually need. This regex finds strings containing any numbers, letters and dashes. Only the string cannot start or end with a dash.

$name = 'BenQ -1G2-420H-DBL- 23.6" Wide LCD Monitor';
$a = preg_match('/\b(([0-9A-Z]+[A-Z0-9]+)[-]*)+\b/i', $name, $m);

var_dump($m[0]);


Ended up using this, just had to str_replace the dashes. @codaddict The regex formula was just a split second slower than this one.

$str = "BenQ G2420HDBL 23.6";
$pieces = split(' ', $str);
$theStr = '';
foreach($pieces as $piece) {
    if(!ctype_alpha($piece) && !ctype_digit($piece) && ctype_alnum($piece)) {
        $theStr = $piece;
        break;
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜