在文本中查找相应的字符串

时间:2016-01-31 18:11:53

标签: php regex laravel

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

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时,它还需要找到相应的金额。关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分: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。如果您需要更多提供者,请提供更多预期的输入字符串。