php preg_split() to find text inbetween two words

帅比萌擦擦* 提交于 2020-01-16 18:34:17

问题


how do I use preg_split() to grab the value between [item:1] and [/item:1]
$query= [item:1] my content [/item:1];

This isn't working
$match = preg_split('/[[item:1][\/item:1]]/', $query);
echo $match[0];

output should be just " my content ".

UPDATE:


$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:


You don't want to split the string, you want to capture a pattern. For that, use preg_match, eg

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

Edit: Tested and working

Edit2: Added "s" (PCRE_DOTALL) modifier - http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php.

You should really consider a better markup solution (see XML)



来源:https://stackoverflow.com/questions/4988474/php-preg-split-to-find-text-inbetween-two-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!