【问题标题】:Find corresponding strings in text在文本中查找对应的字符串
【发布时间】:2016-01-31 18:11:52
【问题描述】:

我需要构建一个导入功能,用户可以在其中提交文本(账单),该功能将找到税款和金额。所以假设输入了这个文本(这是我们处理的实际文本):

DateAmountDescription 
24-01-2016$ 14,99Spotify 
23-01-2016$ 10,50Netflix
23-01-2016$ 5,50Amazon

我发现下面的代码将字符串与我们存储的关键字进行比较:

foreach ($keywords as $keyword) 
{
    $pos = strpos($text, $keyword);

    if ($pos === false) {

    } else {
        echo "The string '$keyword' was found in the string.";
        echo " and exists at position $pos<br>";
    }
}

这将输出:The string Spotify was found in the string. and exists at position 39. 现在,在此之后我需要做的是,我还想找到金额。所以当函数找到 Spotify 时,也需要找到对应的金额。关于如何做到这一点的任何想法?

【问题讨论】:

  • 你的意思是在这个例子中,spotify 将有 14,99 美元?
  • 是的,Spotify 会有 14,99。 Netflix 10,50 和亚马逊 5,50。

标签: php regex laravel


【解决方案1】:

使用正则表达式解决方案:

<?php

$string = "DateAmountDescription 
24-01-2016$ 14,99Spotify 
23-01-2016$ 10,50Netflix
23-01-2016$ 5,50Amazon";

$regex = '~(?<amount>[\d,.]+)(?<provider>Spotify|Netflix|Amazon)\s*$~m';
# look for Spotify or Netflix or Amazon at the end of a line (+/- whitespace)
# capture it in the group "provider"
# look for anything that is a digit (\d), dot or comma BEFORE
# capture this to the group "amount"

preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    echo "Found: " . $match["provider"] . " with amount: " . $match["amount"] . "\n";
}
// output
// Found: Spotify with amount: 14,99
// Found: Netflix with amount: 10,50
// Found: Amazon with amount: 5,50

?>

要查看在线演示,请访问regex101.com。如果您需要更多提供者,请提供更多预期的输入字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2015-07-14
    • 2016-11-14
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多