【发布时间】:2013-08-14 04:23:36
【问题描述】:
当然,这已经被其他人问过了,但是我在 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(),但我认为正则表达式可能会更好更快。
【问题讨论】:
-
刚回到这里,因为这个问题已经超过了 1000 次浏览。只是想知道为什么它得到了反对票:它显示了我在搜索类似问题方面的努力,并且我提供了我的代码。
标签: php regex string parsing words