PHP检测和替换

时间:2017-01-20 12:32:35

标签: php

请告诉我如何从字符串中检测出int,然后用值替换每个int? 例如,我有这个" 1; 5; 81; 2"在数据库中,我想用一个特定的值替换每个数字,例如我想得到的结果" o b z q" 有没有办法做到这一点?感谢

1 个答案:

答案 0 :(得分:0)

创建一个包含键值对的数组,其中键是数字,值是相应的字母。然后在字符串上使用带有数字的php函数explode()并循环遍历数组,用相应的字母替换数字。

示例:

$numberLetterArray = array(
    1 => 'o',
    2 => 'q',
    5 => 'b',
    81 => 'z',
);

$string = '1;5;81;2';

// Creates an array of only the numbers
$numbers = explode(';', $string);

foreach($numbers as $n)
{
    foreach($numberLetterArray as $number=>$letter)
    {
        if($number == $n)
        {
            $output .= $letter.' ';
        }
    }
}

// Remove the space at the end
$output = trim($output);

那应输出“o b z q”。