Home > Blockchain >  Replace the field
Replace the field

Time:11-24

I am using the following code:

function my_map_field( $data ) {
    $map = array(
        'Toys for 12 years old' => '12 ',
        'Toys for 4 years old' => '4 ',
        'Toys for 7 years old' => '7 ',
        'Toys for 9 years old' => '9 ',
    );
    return isset( $map[$data] ) ? $map[$data] : null;
}

It replaces: Toy for 12 years old ---> 12

I need to change the exact text mapping ('Toys for 12 years old') to if the field contains ('12 years')

for example: if the field contains 12 years write 12 ; if the field contains 7 years write 7 . If nothing is found, leave empty

Thanks

CodePudding user response:

Match exact word

function my_map_field( $data ) {
    $map = array(
        'Toys for 12 years old' => '12 ',
        'Toys for 4 years old' => '4 ',
        'Toys for 7 years old' => '7 ',
        'Toys for 9 years old' => '9 ',
    );

    foreach ($map as $text => $number) {
        if (stripos($text, $data) !== false) {
            return $map[$text];
        }
    }
    return '';
}

echo my_map_field('7 years');// result is 7 
echo my_map_field('11 years');// result is empty
echo my_map_field('12 years');// result is 12 

Match any number with year[s]

function my_map_field( $data ) {
    $map = array(
        'Toys for 12 years old' => '12 ',
        'Toys for 4 years old' => '4 ',
        'Toys for 7 years old' => '7 ',
        'Toys for 9 years old' => '9 ',
    );

    preg_match('/(\d )\s*year[s]?/i', $data, $matches);
    $matchNumber = ($matches[1] ?? '');

    foreach ($map as $text => $number) {
        if (stripos($text, $matchNumber) !== false) {
            return $map[$text];
        }
    }
    return '';
}

echo my_map_field('buy toys for 12 years old');// get 12 
echo my_map_field('used toys for 12 years old');// get 12 
echo my_map_field('buy toys for 15 years old');// get empty.
  • Related