提取两个值之间的所有字符串

时间:2020-03-24 09:06:32

标签: php

我尝试从两个值之间的文本中提取所有值,例如:public function get_string_between($string, $start, $end) { $string = ' ' . $string; $ini = strpos($string, $start); if ($ini == 0) return ''; $ini += strlen($start); $len = strpos($string, $end, $ini) - $ini; return substr($string, $ini, $len); } $fullstring = '[{"content":{"content":"<h1>Acceptances<\/h1>","numbering":""},"children":[{"content":{"content":"<p><span>Ownership of the Products remains with the [X] and will not pass to the [Y] until one of the following events occurs:<\/span><\/p>","numbering":""},"children":[{"content":{"content":"<p><span>The [X] is paid for all of the Products and no other amounts are owed by the [Y] to the [X] in respect of other Products supplied by the [X].<\/span><\/p>","numbering":""},"children":[]},{"content":{"content":"<p><span>The [Y] sells the Products in accordance with this agreement in which case ownership of the Products will pass to the [Y] immediately before the Products are delivered to the [Y]&#039;s customer.<\/span><\/p>","numbering":""},"children":[]}]},{"content":{"content":"<p><span>Where the Products are attached to or incorporated in other Products or are altered by the [Y], ownership of the Products shall not pass to the [Y] by virtue of the attachment, incorporation or alteration if the Products remain identifiable and, where attached to or incorporated in other Products, can be detached or removed from them.<\/span><\/p>","numbering":""}'; $paragraph_start_1 = '<p>'; $paragraph_end_2 = '<\/p>'; $paragraph = $this->get_string_between($fullstring, $paragraph_start_1, $paragraph_end_2); //The output is just the first one and I need all. / ^\+?3?8?(0[\s\.-]\d{2}[\s\.-]\d{3}[\s\.-]\d{2}[\s\.-]\d{2})$ 现在,我只能提取第一个。

public class Party
{
    public string Type { get; set; }
    public string Name { get; set; }
}

2 个答案:

答案 0 :(得分:1)

使用正则表达式代替:

template<class T, class M>
void add2_member(T& value, M member)
{
    value.*member += 2;
}

template<class T, auto ... Members>
void add2(T& value)
{
    (add2_member(value, Members), ...);
}

如果要测试正则表达式:

public function get_string_between($string, $start, $end)
{
    $re = $start.'(.*?)'.$end.'/m';

    preg_match_all($re, $string, $matches, PREG_SET_ORDER, 0);

    return($matches);
}

答案 1 :(得分:1)

如果您完全确定输入字符串始终遵循相同的格式,则仅将正则表达式用作此类问题的解决方案。例如:总是一个

但位置未知。

否则,请使用本机DOM或XML解析器提取文本。 看到这个广泛的答案:How do you parse and process HTML/XML in PHP?