php在单词“”之后和之前的字符串中查找数字;欧元”;


php find numbers in a string after and before the word "euro"

我有一个类似"9 mesi in cotone EURO 3+ss""9 mesi in cotone 3 EURO +ss"的字符串,我想在单词EURO之前或之后获得整数值,这取决于字符串格式(我不知道用户将如何发送)有人能帮我吗?

类似这样的东西:

if(preg_match('/(''d+(?:'.''d+)?)?''s*euro''s*(''d+(?:'.''d+)?)?/i', $string, $regs) and count($regs) > 1) {
    if(!$regs[1] and !$regs[2]) {
        // Invalid input
    } else {
        $amount = floatval($regs[1] ? $regs[1] : $regs[2]);
        // Do something with $amount
    }
}

正则表达式可能需要根据区域设置进行调整(空格为千个分隔符、逗号等)。

如果使用整数值,正则表达式简化为:

preg_match('/(''d+)?''s*euro''s*(''d+)?/i', $string, $regs)
preg_match_all('/[0-9]+/',$string,$matches);
$values = array_shift($matches);
$lastnum = array_pop($values);
echo $lastnum;

将其分解为两个正则表达式可能更简单:

/(d+)'s*EURO/
/EURO's*(d+)/

这应该会让你走上正轨。