我的工作是通过Twilio接收传入的SMS消息并且基于哈希标签,并设置用户偏好的PHP应用程序。例如,如果用户想要禁用网站的短信提醒,他们会发送短信#sms off
。用#标签切换设置,PHP
下面是我已经把处理这个任务的代码,但我觉得这是臃肿,并且可以清理一下。将不胜感激任何关于如何从另一个(希望更加整洁)角度来处理这个任务的建议。
这很棘手,因为即将到来的hashtag可以在任何cAsE - #SMS off
,#Sms Off
,等我通过使命令和设置大写处理此。
这里是我迄今为止 -
<?php
$body = trim($_POST['Body']);
$pos = strripos($body, '#'); //Find position of hashtag in body
if ($pos != 0) {
//Hashtag was not first, therefor this is a normal incoming SMS
//without commands
echo "Normal SMS message";
} else if ($pos == 0) {
//This is a command SMS, we need to react to it
preg_match_all('/#(\w+)/',$body,$matches); // Isolate the hashtag
// Change hashtag, complete with #, to uppercase
//This is to prevent case issues in the incoming SMS
$command = strtoupper($matches[0][0]);
//Remove the hashtag from the SMS, convert the remaining string to upper,
//and trim it to isolate
$setting = str_ireplace($command, '', $body);
$setting = strtoupper(trim($setting));
//Switch for available commands
switch ($command) {
case '#DISPATCH':
if ($setting == 'ON') {
echo 'Dispatch alert has been turned on';
} else if ($setting == 'OFF') {
echo 'Dispatch alert has been turned off';
} else {
'Missing setting. Please reply with #dispatch on or #dispatch off to set.';
}
break;
case '#SMS':
if ($setting == 'ON') {
echo 'SMS alerts have been turned on';
} else if ($setting == 'OFF') {
echo 'SMS alerts have been turned off';
} else {
'Missing setting. Please reply with #sms on or #sms off to set.';
}
break;
default:
echo 'I do not recognize this command. Please enter either #dispatch or #sms followed by on or off to set.';
break;
}
}
谢谢!
我喜欢它除了一个缺点 - 如果有以下的井号标签多于一个的空间,设置不包含 – NightMICU
好吧,我更新了答案。抓住第一个数组元素作为命令很容易,然后将它们拼接在一起。一般来说,我发现使用数组比字符串操作更容易。 – jszobody
现在就来,谢谢!似乎是做工精细,部署:) – NightMICU