解析2个单词之间的文本

Gio*_*gio 3 php regex string parsing words

可以肯定的是,其他人已经问过这个问题,不过我在这里搜索了SO并且没有找到任何内容https://stackoverflow.com/search?q=php+parse+between+words

我有一个字符串,想要一个包含2个分隔符(2个单词)之间所有单词的数组.我对正则表达式没有信心所以我最终得到了这个解决方案,但它不合适,因为我需要得到符合这些要求的所有单词,而不仅仅是第一个.

$start_limiter = 'First';
$end_limiter = 'Second';
$haystack = $string;

# Step 1. Find the start limiter's position

$start_pos = strpos($haystack,$start_limiter);
if ($start_pos === FALSE)
{
    die("Starting limiter ".$start_limiter." not found in ".$haystack);
}

# Step 2. Find the ending limiters position, relative to the start position

$end_pos = strpos($haystack,$end_limiter,$start_pos);

if ($end_pos === FALSE)
{
    die("Ending limiter ".$end_limiter." not found in ".$haystack);
}

# Step 3. Extract the string between the starting position and ending position
# Our starting is the position of the start limiter. To find the string we must take
# the ending position of our end limiter and subtract that from the start limiter
$needle = substr($haystack, $start_pos+1, ($end_pos-1)-$start_pos);

echo "Found $needle";
Run Code Online (Sandbox Code Playgroud)

我还想过使用explode(),但我认为正则表达式可以更好更快.

Jer*_*rry 8

我对PHP并不熟悉,但在我看来,你可以使用类似的东西:

if (preg_match("/(?<=First).*?(?=Second)/s", $haystack, $result))
    print_r($result[0]);
Run Code Online (Sandbox Code Playgroud)

(?<=First)看起来落后First但不消耗它,

.*?在捕捉之间的一切FirstSecond,

(?=Second)展望未来,Second但不消耗它,

s在年底是使点.匹配换行符(如有).


要获取这些分隔符之间的所有文本preg_match_all,您可以使用循环来获取每个元素:

if (preg_match_all("/(?<=First)(.*?)(?=Second)/s", $haystack, $result))
    for ($i = 1; count($result) > $i; $i++) {
        print_r($result[$i]);
    }
Run Code Online (Sandbox Code Playgroud)