Php 拨弄每一根弦

Php 拨弄每一根弦,php,regex,preg-match-all,Php,Regex,Preg Match All,下面是一个函数,它可以毫无问题地获取一个字符串和另外两个字符串 function GetBetween($content,$start,$end){ $r = explode($start, $content); if (isset($r[1])){ $r = explode($end, $r[1]); return $r[0]; } return ''; } 假设我有这样的代码: <code>Sample one&l

下面是一个函数,它可以毫无问题地获取一个字符串和另外两个字符串

function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}
假设我有这样的代码:

<code>Sample one</code>
<code>Sample two</code>
<code>Sample three</code>
当使用
GetBetween($content,“
”,
”)
而不是返回类似
数组(“示例一”、“示例二”、“示例三”)
的内容时,它将只返回第一个,即“示例一”
如何让它返回我指定的两件事之间的所有内容?如果我能得到一个不使用“”标签硬编码的解决方案,我将不胜感激,因为我需要它来处理许多不同的事情

我不得不使用这样的函数,所以我把它放在手边:

//where a = content, b = start, c = end
function getBetween($a, $b, $c) {
    $y = explode($b, $a);
    $len = sizeof($y);
    $arr = [];
    for ($i = 1; $i < $len; $i++)
        $arr[] = explode($c, $y[$i])[0];
    return $arr;
}
//其中a=内容,b=开始,c=结束
函数getBetween($a、$b、$c){
$y=爆炸($b,$a);
$len=sizeof($y);
$arr=[];
对于($i=1;$i<$len;$i++)
$arr[]=爆炸($c,$y[$i])[0];
返回$arr;
}

除此之外,您还需要开始使用。

首先
regex
不是解析
HTML/XML
的正确工具,您可以简单地使用
DOMDocument
,如下所示

$xml = "<code>Sample one</code><code>Sample two</code><code>Sample three</code>";

$dom = new DOMDocument;
$dom->loadHTMl($xml);
$root = $dom->documentElement;
$code_data = $root->getElementsByTagName('code');
$code_arr = array();
foreach ($code_data as $key => $value) {
    $code_arr[] = $value->nodeValue;
}
print_r($code_arr);
输出:

Array
(
    [0] => Sample one
    [1] => Sample two
    [2] => Sample three
)

我想你可以试试这样的

function GetBetween($content,$tagname){
        $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
        preg_match($pattern, $string, $matches);
        unset($matches[0]);
        return $matches;
}

$content= "<code>Sample one</code><code>Sample two</code><code>Sample three</code>";

//The matching items are: 
print_r(GetBetween($content, 'code'));

我想你应该在函数中添加一个循环。你想解码XML吗?你想把字符串作为输出吗?这对我有用,非常感谢!它甚至可以与高级标记一起使用,例如