当然,这已经被其他人问过了,但是我在 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() 但我认为正则表达式可能会更好更快。