Search code examples
phparraysvalidationsanitization

Convert numeric words embedded in strings into their integer equivalent, then validate the mutated strings


I trying to convert array value with word into numeric. Then filtering it with regex and getting original value for matched array element. I have tried in my way. There may be better way to do this.

$arrwords = array(
    0 => 'zero',
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
    5 => 'five',
    6 => 'six',
    7 => 'seven',
    8 => 'eight',
    9 => 'nine'
);
$arr = array('124', '8989243three', '402three1345233', '4023one34523');
$arr2 = array();
foreach($arr as $v)
{
    $v = strtolower($v);
    if (in_array($v, $arrwords))
    {
        $arr2_push() = str_replace($v, array_search($v, $arrwords), $text); //replace word with digit and push into $arr_2 . 
    }
}

//Now check each value int arr2 to with regex
foreach ($arr2 as $temp) {
    $pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
    preg_match_all($pattern, $temp, $matches, PREG_OFFSET_CAPTURE );

    //If $temp matches with filter then push into $arr3

Now getting values from $arr1 which belongs to value in $arr3.

Example: [3] => 4023one34523 from $arr1 will be in $arr3 as 4023134523. So value three should be considered. likewise all value.

So bottom line

  1. Convert word into number to numeric digit
  2. Match number with regex
  3. For matched numbers get original value in form of array

Solution

  • Here is mine :)

    <?php
    
    $words = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
    // Hash is faster than in_array, especially on large sets.
    $words = array_flip($words);
    $test = array(
        124,
        '89889three6four',
        '402one1',
        'five'
    );
    
    $b = array();
    $pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
    foreach ($test as $value) {
        $value = strtolower($value);
        // Capture also the numbers so we just concat later, no more string substitution.
        $matches = preg_split('/(\d+)/', $value, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    
        if ($matches) {
            $newValue = array();
            foreach ($matches as $word) {
                // Replace if a valid word number.
                $newValue[] = (isset($words[$word]) ? $words[$word] : $word);
            }
            $newValue = implode($newValue);            
            if (preg_match($pattern, $newValue)) {
                $b[] = $value;
            }
        }
    }
    
    echo implode("\n", $b);