下面是一个函数,它可以毫无问题地获取带有另外两个字符串的字符串,
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>')
时,它不会返回类似 array("Sample one","Sample two","Sample three")
的内容,它只会返回第一个"示例一"如何让它返回我指定的两件事之间的所有内容?如果我能得到一个不使用"标签硬编码的解决方案,我将不胜感激,因为我将需要它来处理许多不同的事情。
首先,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
)
我不得不使用这样的函数,所以我把它放在手边:
//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。
猜猜你可以尝试这样的事情,
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'));