Extract content from a sentence in PHP

0

Good morning, I wanted to ask you how I can extract the content of a sentence in PHP.

Example:

Chandal de pepe por sólo 3,50€

I need to extract the price from pepe's tracksuit, the prices can sometimes contain up to 3 or 5 digits and other times it may or may not contain decimal . I'm not sure if it is extracted with a preg_match() or with another function in PHP

    
asked by Fumatamax 02.02.2018 в 13:25
source

2 answers

3

First clean special characters (tildes etc). Then remove everything that is letters. Replaces the € symbol. And now that you only have the number, cast it to float.

<?php


$str = 'Chandal de pepe por sólo 3.50€';
$double = cleanString($str);
$double = preg_replace('/[a-z]/i','',$double); 
$double = str_replace('€','',$double); 

$float = (float)$double;

echo $float; // 122.34343



function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

?>
    
answered by 02.02.2018 / 13:39
source
0

Regex:

/\d+(?:[.,]\d+)*(?=[€$])/u
  • \d+ 1 or more digits.
  • (?:[.,]\d+)* followed by 0 or more repetitions of:
    • [.,]\d+ a period or comma, followed by 1 or more digits.
  • (?=[€$]) that is followed by (but not coincident with) or $ .
  • Modifier u : text and pattern in Unicode (to match the as the only character).


Code:

$texto = "Chandal de pepe con descuento del 10%, por sólo 3,50€!!!";

if ( preg_match ( '/\d+(?:[.,]\d+)*(?=[€$])/u' , $texto, $match ) ) {
    $precio = $match[0];
    echo $precio;
}

Result:

3,50
    
answered by 07.02.2018 в 15:06