【问题标题】:Get between every strings在每个字符串之间获取
【发布时间】:2016-05-31 14:02:57
【问题描述】:

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

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

【问题讨论】:

  • 我认为你应该在函数中添加一个循环
  • 您是否在尝试解码 XML?
  • 你想要字符串作为输出吗?

标签: php regex preg-match-all


【解决方案1】:

首先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
)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这对我有用,非常感谢!它甚至适用于高级标签,例如

    【解决方案3】:

    你可以试试这样的,

    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'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 2019-05-12
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多