在段落中如何使用PHP查找给定字符串之间的字符串?

时间:2018-03-30 06:07:38

标签: php arrays regex string match

In paragraph how to find strings between the given strings using php ?

另存为siva.txt

Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt SIVA ut labore et dolore magna aliqua。 Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat。 Duis aute irure dolor in repreptderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur。 Excepteur PRABU sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum Lorem ipsum dolor sit amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。 Duis aute irure dolor

in repreptderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 xcepteur sint occaecat cupidatat non proident,SIVA sunt in culpa qui

officia deserunt mollit anim id est laborum PRABU

2 个答案:

答案 0 :(得分:1)

它总是一样的,真​​的:

SIVA((?s).*?)PRABU
# look for SIVA
# ((?s) ... ) forms a capturing group where the dot matches everything
# .*? is lazy
# match until PRABU is found

使用第一组并查看a demo on regex101.com

<小时/> 在PHP

$regex = '~SIVA((?s).*?)PRABU~';
if (preg_match_all($regex, $data, $matches)) {
    print_r($matches[1]);
}

这会产生

Array
(
    [0] =>  ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur 
    [1] =>  sunt in culpa qui

officia deserunt mollit anim id est laborum 
)

答案 1 :(得分:1)

我喜欢Jan用正则表达式给出的答案。我试过自定义编码。为了记录,我们去了。

$text = "Lorem ipsum dolo ... it anim id est laborum PRABU";
//$text should have all the text.
$keys = array('SIVA','PRABU');
$startPos = 0;
$endPos = 0;
$arr = [];
while($startPos < strlen($text)){
    $startPos = strpos($text, $keys[0], $startPos);
    if($startPos === false){
        break;
    }
    $startPos += strlen($keys[0]);
    $endPos = strpos($text, $keys[1], $endPos);
    $data = substr($text,$startPos, $endPos - $startPos);
    array_push($arr,$data);
    $endPos += strlen($keys[1]);
}

结果如下

echo "<pre>";
print_r($arr);
echo "</pre>";