字符串搜索通过正则表达式?没有更好的办法了


string search via regex ? any better way?

我想在php中搜索一个特殊条件的文本文件:当第一次字符串匹配时,开始收集文本,当第二次相同的字符串匹配时,停止收集文本。

。如果字符串是'world'并在下面行搜索:我们的世界有196个国家,但其中只有192个是联合国成员国。我们的世界是非凡的。

然后我想要这个文本:'有196个国家,但其中只有192个是联合国成员国。我们的' in匹配变量。

我在preg_match()中尝试了许多正则表达式,但没有结果,所以有没有更好的方法来做到这一点?

谢谢

使用前后视图:

/(?<=world ).*?(?= world)/

在这里看到它的行动:http://regex101.com/r/tW2bT8


…下面是一个使用PHP的演示:http://codepad.viper-7.com/DucTKE

$lines = file($filename);
$keep = false;
$keepTrailing = true; //Flag that decides wether to keep trailing capture segments or not.
$extractions = array();
$current = '';
foreach($lines as $line){
    $parts = preg_split('/'bworld'b/i', $line);
    $current .= $parts[0];
    for ($i = 1; $i<count($parts); $i++){
        if ($keep) $extractions[] = $current;
        $keep = !$keep;
        $current = $parts[$i];
    }
}
if ($keep && $keepTrailing)
    $extractions[] = $current;
var_dump($extractions);

下面是它的作用。

基本上,通过对文件进行一次迭代,您可以简单地在关键字("world")上拆分每行—我使用'b锚来确保它不会在"world"或其他垃圾上拆分。我包含了一个标志来决定是否保留跟踪捕获段。你不一定需要它,但它可能会有所帮助。该解决方案中唯一不直观的部分是将当前捕获保存在$current变量中,这基本上允许您跨多个换行符进行扫描。

你知道,这很容易变成一个函数。

function capturingSearchWithKeyword($filename, $keyword, $keepTrailing = true, $trim = false){
    $lines = file($filename);
    $keep = false;
    $extractions = array();
    $current = '';
    foreach($lines as $line){
        $parts = preg_split("/''b$keyword''b/i", $line);
        $current .= $parts[0];
        for ($i = 1; $i<count($parts); $i++){
            if ($keep){
                if ($trim) $current = trim($current);
                $extractions[] = $current;
            }
            $keep = !$keep;
            $current = $parts[$i];
        }
    }
    if ($keep && $keepTrailing)
        $extractions[] = $current;
    return $extractions
}