PHP preg_match指定数字,并通过特定数字的区域获取节id


PHP preg_match specify number and get the section id by the area of the specific number

我想根据入口编号从文本中获取节id时期

<li id="section-1" role="example" label="1 - 6">
<li id="section-2" role="example" label="6 - 12">
<li id="section-3" role="example" label="12 - 18">
<li id="section-4" role="example" label="18 - 24">

例如,当我进入8时,时间段将是6-12,我将得到"第2节",21将得到"第4节

你可以试试这样的东西:

<?php
$text = '<li id="section-1" role="example" label="1 - 6">
<li id="section-2" role="example" label="6 - 12">
<li id="section-3" role="example" label="12 - 18">
<li id="section-4" role="example" label="18 - 24">';
$pattern = '<li id="section-([0-9]+)" role="example" label="([0-9]+) - ([0-9]+)">';
function find_section($value) {
    global $text, $pattern;
    preg_match_all($pattern, $text, $results);
    $index = 0;
    foreach($results[3] as $max) {
        if ($value < $max) {
            break;
        }
        $index++;
    }
    return "section-{$results[1][$index]}   {$results[2][$index]} - {$results[3][$index]}'n";
}
echo find_section(6);  // section-2   6 - 12
echo find_section(21); // section-4   18 - 24

http://ideone.com/uCzCkm

假设你知道自己在做什么,我会选择这样的函数:

function find_section($html, $value)
{
    static $pattern = '/<li id="section''-(''d+)" role="example" label="(''d+) '- (''d+)"(>)/';
    $offset = 0;
    while (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $offset))
    {
        $section_id = (int) $matches[1][0];
        $range_min = (int) $matches[2][0];
        $range_max = (int) $matches[3][0];
        $offset = $matches[4][1] + 1;
        if ($value >= $range_min && $value < $range_max)
        { return 'section-' . $section_id; }
    }
    return null;
}

我个人不知道有没有可能打一个preg_match电话。我认为这是不可能的。上面的函数将扫描给定的HTML字符串以查找li-元素的模式,提取它们的范围,并将给定的值与之进行比较

根据您实际想要实现的目标,例如,如果您正在搜索多个值的部分,您可能希望第一次扫描所有li-元素,并将它们存储为更容易访问的数据(例如数组或stdclass对象),这样您就不必每次搜索值的部分时都重新匹配整个HTML代码。

上面函数的一个简单的小测试代码(只是为了展示它是如何工作的)是:

$html = '
    <li id="section-1" role="example" label="1 - 6">
    <li id="section-2" role="example" label="6 - 12">
    <li id="section-3" role="example" label="12 - 18">
    <li id="section-4" role="example" label="18 - 24">
';
echo find_section($html, 8) . "'n";
echo find_section($html, 21) . "'n";
echo find_section($html, 50) . "'n";

输出:

section-2
section-4

(用PHP 5.5.15测试)