按关键字过滤文本 php

问题描述 投票:0回答:1

我想编写一些接受两个参数 $text 和 $keys 的函数。键是带有键的数组。

在输出中,我们需要获取一个数组,其中键将是传递给函数的键(如果我们在文本中找到它们),值将是该键后面的文本,直到遇到它下一个键或文本结束。如果文本中的键重复,则仅将最后一个值写入数组

例如:

$text = 'Lorem Ipsum is simply **one** dummy text of the printing and  **two** typesetting industry. Lorem Ipsum has been the industry's  **one** standard dummy text ever since the **three** 1500s.';

$keys = [`one`,`two`, `three`];

$output = [`one` => `standard dummy text ever since the`,`two` => `typesetting industry. Lorem Ipsum has been the industry's`, `three` => `1500s.`];

我尝试编写正则表达式。它将处理这个任务,但没有成功。

最后一次尝试:

function getKeyedSections($text, $keys) {
$keysArray = explode(',', $keys);
$pattern = '/(?:' . implode('|', array_map('preg_quote', $keysArray)) . '):\s*(.*?)(?=\s*(?:' . implode('|', array_map('preg_quote', $keysArray)) . '):\s*|\z)/s';
preg_match_all($pattern, $text, $matches);

$keyedSections = [];
foreach ($keysArray as $key) {
    foreach ($matches[1] as $index => $value) {
        if (stripos($matches[0][$index], $key) !== false) {
            $keyedSections[trim($key)] = trim($value);
            break;
        }
    }
}

return $keyedSections;

}

php text-parsing
1个回答
0
投票

需要交钥匙吗?这个如何将键附加在文本中出现的位置:

<?php 


$text = "Lorem Ipsum is simply **one** dummy text of the printing and  **two** typesetting industry. Lorem Ipsum has been the industry's  **one** standard dummy text ever since the **three** 1500s.";

$matches = [];
preg_match_all("/(\*\*(\w|\d)+\*\*)(\w|\d|\s)+/", $text, $matches);

$actualMatches = $matches[0];
$keys = $matches[1];
$index = 0;

$results = array_reduce($actualMatches, function($carry, $item) use ($keys, &$index) {
    $key = $keys[$index];
    $carry[str_replace("*", "", $key)] = trim(substr($item, strlen($key)));
    $index++;
    return $carry;
}, []);

var_dump($results);

?>

如果您只需要特定的按键,这里有一个替代方案:

<?php 


$text = "Lorem Ipsum is simply **one** dummy text of the printing and  **two** typesetting industry. Lorem Ipsum has been the industry's  **one** standard dummy text ever since the **three** 1500s.";

$matches = [];
preg_match_all("/(\*\*(\w|\d)+\*\*)(\w|\d|\s)+/", $text, $matches);

$actualMatches = $matches[0];
$keys = $matches[1];
$index = 0;

$targetKeys = ['one', 'three'];
$results = array_reduce($actualMatches, function($carry, $item) use ($keys, &$index, $targetKeys) {
    $key = $keys[$index];
    $cleanedKey = str_replace("*", "", $key);
    if (in_array($cleanedKey, $targetKeys)) {
        $carry[str_replace("*", "", $key)] = trim(substr($item, strlen($key)));
    }
    $index++;
    return $carry;
}, []);



var_dump($results);
© www.soinside.com 2019 - 2024. All rights reserved.