可以肯定的是,这已经被其他人问过,但是我在这里搜索了 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";
我也考虑过使用 explode(),但我认为正则表达式会更好更快。
最佳答案
我不太熟悉 PHP,但在我看来你可以使用类似这样的东西:
if (preg_match("/(?<=First).*?(?=Second)/s", $haystack, $result))
print_r($result[0]);
(?<=First)
回头寻找First
但不消耗它,
.*?
捕获 First
之间的所有内容和 Second
,
(?=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]);
}
关于php - 解析两个词之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18194080/