php - 解析两个词之间的文本

标签 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";

我也考虑过使用 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/

相关文章:

c# - 使用 RegEx 从字符串中删除编码的 HTML

python - 向列表中的项目添加空格(Python)

javascript - 奇怪的 Javascript 字符串操作行为

javascript - 如何每隔一小时更新变量而不由用户刷新页面?

javascript - 使用 php session 的事件 session 中菜单列表的方法

Javascript: replace() all 但仅在 html 标签之外

c++ - 编写正则表达式模式 C++

c++ - 当许多 unordered_map<string, double> 具有完全相同的字符串设置为键时如何节省内存

PHP PDO : Undefine variable

php - 用 html 附上 echo