我有一个函数,可以检查字符串(参数)是否与数组中的值匹配并返回可能性键的数组
function find_possible_match( $criteria ) {
$possible_match = array();
$possibilities = array(
"a"=>".-",
"b"=>"-...",
"c"=>"-.-.",
"d"=>"-..",
"e"=>".",
"f"=>"..-.",
"g"=>"--.",
"h"=>"....",
"i"=>"..",
"j"=>".---",
"k"=>"-.-",
"l"=>".-..",
"m"=>"--",
"n"=>"-.",
"o"=>"---",
"p"=>".--.",
"q"=>"--.-",
"r"=>".-.",
"s"=>"...",
"t"=>"-",
"u"=>"..-",
"v"=>"...-",
"w"=>".--",
"x"=>"-..-",
"y"=>"-.--",
"z"=>"--..",
"0"=>"-----",
"1"=>".----",
"2"=>"..---",
"3"=>"...--",
"4"=>"....-",
"5"=>".....",
"6"=>"-....",
"7"=>"--...",
"8"=>"---..",
"9"=>"----.",
"."=>".-.-.-",
","=>"--..--",
"?"=>"..--..",
"/"=>"-..-.",
" "=>" ");
foreach ( $possibilities as $key => $value ) {
if( $value == $criteria ){
array_push( $possible_match , $key );
}
}
return $possible_match;
}
这是非常标准的,是字符串之类的所有标准
find_possible_match( ".-" );
将返回[a]...等
但问题在于,如果参数有一个未知的示例怎么办
find_possible_match("?");
同样应该返回[e, t]
find_possible_match("?.")
应返回 ['i','n'] 和
find_possible_match(".?")
应该返回['i','a']
?在本例中是通配符。 我如何修改上面的代码来做到这一点。谢谢
最佳答案
您可以使用 preg_match()
检查 $criteria 是否与 $value
匹配。您可以根据正则表达式要求替换 $criteria
(转义点,将 ?
转换为 [.-]
):
function find_possible_match( $criteria ) {
$criteria = str_replace(['.','?'],['\.','[.-]'],$criteria);
$regexp = '~^'.$criteria.'$~';
$possibilities = array(
"a"=>".-",
"b"=>"-...",
"c"=>"-.-.",
"d"=>"-..",
"e"=>".",
"f"=>"..-.",
"g"=>"--.",
"h"=>"....",
"i"=>"..",
"j"=>".---",
"k"=>"-.-",
"l"=>".-..",
"m"=>"--",
"n"=>"-.",
"o"=>"---",
"p"=>".--.",
"q"=>"--.-",
"r"=>".-.",
"s"=>"...",
"t"=>"-",
"u"=>"..-",
"v"=>"...-",
"w"=>".--",
"x"=>"-..-",
"y"=>"-.--",
"z"=>"--..",
"0"=>"-----",
"1"=>".----",
"2"=>"..---",
"3"=>"...--",
"4"=>"....-",
"5"=>".....",
"6"=>"-....",
"7"=>"--...",
"8"=>"---..",
"9"=>"----.",
"."=>".-.-.-",
","=>"--..--",
"?"=>"..--..",
"/"=>"-..-.",
" "=>" ");
$possible_match = array();
foreach ($possibilities as $key => $value) {
if (preg_match($regexp, $value)) {
array_push($possible_match, $key);
}
}
return $possible_match;
}
print_r(find_possible_match(".-")); // ['a']
print_r(find_possible_match("?")); // ['e','t']
print_r(find_possible_match("?.")); // ['i','n']
print_r(find_possible_match(".?")); // ['i','a']
输出:
Array
(
[0] => a
)
Array
(
[0] => e
[1] => t
)
Array
(
[0] => i
[1] => n
)
Array
(
[0] => a
[1] => i
)
关于php - 使用以问号作为通配符的输入查找潜在的莫尔斯电码字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49795760/