穿梭在每根弦之间

Get between every strings

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

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,'<code>',</code>') 而不是 return 像 array("Sample one","Sample two","Sample three") 这样的东西时,它只会 return 第一个 "Sample one" 我怎样才能得到它 return 我指定的两件事之间的一切?如果我能得到一个没有用“”标签硬编码的解决方案,我将不胜感激,因为我将需要它来处理许多不同的事情。

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

//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;
}

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

首先,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'));