匹配字符串,且不带正则表达式

时间:2019-03-21 20:52:15

标签: php regex match

这是我的字符串,我只想获取“ GG-00”

$html = "
<td class="P12"> n                Gg-08n            </td>
<li class="P13"> n                GG-00n            </li>
<li class="P122"> n                Gt-90n            </li>
<img class="m43" src="../a.img"></img>
//and more like that//
"
preg_match('/[A-Z]{2}-[0-9]{2}/', $html, $output);

我只想得到GG-00,

<li class="P13">

4 个答案:

答案 0 :(得分:2)

应该这样做(假设它总是 两个大写字母,后跟一个连字符和两个数字):

/[A-Z]{2}-[0-9]{2}/

答案 1 :(得分:1)

您需要以下内容:

/[A-Z].-[0-9]./gm

这是php:

<?php

$matches = null;
preg_match('/[A-Z].-[0-9]./m', '<li class="P12"> n                GG-00n            </li>', $matches);
print_r($matches);

答案 2 :(得分:1)

这是您可以做的一件事;

$string = '<li class="P12"> n                GG-00n            </li>';
$string = explode('<li class="P12"> n                ', $string);
$string = explode('            </li>', $string[1]);
$thecode = $string[0];

与此同时,也可以有不同的代码...

答案 3 :(得分:1)

这完全取决于您要提取的内容。如果您只想提取特定的“ GG-00”,则可以使用:

$html = '<li class="P12"> n                GG-00n            </li>';
preg_match('/[A-Z]{2}-[0-9]{2}/', $html, $matches);
print_r($matches);

将输出:

Array ( [0] => GG-00 )

如果您的问题比这种情况更复杂,您还可以考虑阅读HTML DOM并获取所有LI元素

$doc = new DOMDocument();
$doc->loadHTML('<li class="P12"> n                GG-00n            </li>');
$elements = $doc->getElementsByTagName('li');
foreach ($elements as $element) {
    $html = $doc->saveHtml();
    preg_match('/[A-Z]{2}-[0-9]{2}/', $html, $matches);
    print_r($matches);
}