php preg_split()在两个单词之间查找文本

时间:2011-02-14 02:58:48

标签: php regex preg-split

如何使用preg_split()来获取[item:1]和[/ item:1]之间的值
$query= [item:1] my content [/item:1];

这不起作用 $match = preg_split('/[[item:1][\/item:1]]/', $query);
echo $match[0];

输出应该只是“我的内容”。

更新:


$query = '
[page:1]you got page one content[/page:1]
[page:2]you got page two content[/page:2]
';

// parse function
function parse_page($page, $string) {

    // VERY IMPORTANT STRIP OUT ANYTHING THAT WOULD SCREW UP THE PARSE
    $string = str_replace(array("\r", "\n", "\t", "\f"), array('', ''), $string);

    // test the string with the page number
    preg_match('@\[page:'.$page.'\](.*?)\[/page:'.$page.'\]@', $string, $matches);

    // return the match if it succeeded
    if($matches) {
        return $matches;
    }else {
        return false;
    }
}

// if page is set then try and obtain it
if(isset($_GET['p'])) {

    // set the returned parse value to a variable
    $page_dump = parse_page(($_GET['p']), $query);

    // check to see if the match was successful
    if($page_dump[1]) {
        echo $page_dump[1];
    }else {
        echo '0';
    }
}else {

    // parse page 1, if no page specified.
    $page_dump = parse_page('1', $query);

    if($page_dump[1]) {
        echo $page_dump[1];
    }else {
        echo 'no page =(';
    }
}

1 个答案:

答案 0 :(得分:3)

您不想分割字符串,而是想要捕获图案。为此,请使用preg_match,例如

if (preg_match('@\[item:1\](.*?)\[/item:1\]@s', $query, $matches)) {
    echo $matches[1];
}

编辑:经过测试并正常工作

Edit2:添加了“s”(PCRE_DOTALL)修饰符 - http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

您应该考虑更好的标记解决方案(请参阅XML)