2016-04-08 4 views
0

Хорошо, я пытаюсь создать несколько динамический sms-автоответчик с PHP. Прямо сейчас у меня есть базовый запуск и запуск, который может реагировать на отдельные словарные входы. Смотрите здесь:PHP Как сравнивать и активировать функцию

<?php 

/* Include twilio-php, the official Twilio PHP Helper Library, 
* which can be found at 
* http://www.twilio.com/docs/libraries 
*/ 

include('Services/Twilio.php'); 

/* Controller: Match the keyword with the customized SMS reply. */ 
function index(){ 
    $response = new Services_Twilio_Twiml(); 
    $response->sms("Reply with one of the following keywords: 
monkey, dog, pigeon, owl."); 
    echo $response; 
    } 

function monkey(){ 
    $response = new Services_Twilio_Twiml(); 
    $response->sms("Monkey. A small to medium-sized primate that 
typically has a long tail, most kinds of which live in trees in 
tropical countries."); 
    echo $response; 
} 

function dog(){ 
    $response = new Services_Twilio_Twiml(); 
    $response->sms("Dog. A domesticated carnivorous mammal that 
typically has a long snout, an acute sense of smell, and a barking, 
howling, or whining voice."); 
    echo $response; 
} 

function pigeon(){ 
    $response = new Services_Twilio_Twiml(); 
    $response->sms("Pigeon. A stout seed- or fruit-eating bird with 
a small head, short legs, and a cooing voice, typically having gray and 
white plumage."); 
    echo $response; 
} 

function owl(){ 
    $response = new Services_Twilio_Twiml(); 
    $response->sms("Owl. A nocturnal bird of prey with large 
forward-facing eyes surrounded by facial disks, a hooked beak, 
and typically a loud call."); 
    echo $response; 
} 

/* Read the contents of the 'Body' field of the Request. */ 
$body = $_REQUEST['Body']; 

/* Remove formatting from $body until it is just lowercase 
characters without punctuation or spaces. */ 
$result = preg_replace("/[^A-Za-z0-9]/u", " ", $body); 
$result = trim($result); 
$result = strtolower($result); 

/* Router: Match the ‘Body’ field with index of keywords */ 
switch ($result) { 
    case 'monkey': 
     monkey(); 
     break; 
    case 'dog': 
     dog(); 
     break; 
    case 'pigeon': 
     pigeon(); 
     break; 
    case 'owl': 
     owl(); 
     break; 

/* Optional: Add new routing logic above this line. */ 
    default: 
     index(); 
} 

То, что я пытаюсь сделать, чтобы получить это реагировать, если кто-то тексты на что-то вроде: «Эй, что собака на продажу?». На данный момент он работает только в том случае, если текстовое слово «собака» или «собака».

Я возился с массивами, preg_match, stripos/strpos, но не мог для жизни меня заставить его функционировать правильно. Может ли кто-нибудь помочь, по крайней мере, указывая на меня в правильном направлении? Я нахожусь в процессе изучения кода, чтобы исправить мою собственную проблему, потому что не было ни одного доступного, так что медведь со мной, что я новичок в этом.

Вот что у меня есть сейчас, и это все еще не работает, но я чувствую, что это правильное направление. Это просто замена нижней части секции кода:

/* Read the contents of the 'Body' field of the Request. */ 
$body = $_REQUEST['Body']; 

/* Remove formatting from $body until it is just lowercase 
characters without punctuation or spaces. */ 
$result = rtrim($body, ", . ! ?"); 
$result = strtolower($result); 
$result = explode(' ', $result); 
$keyword = array('dog', 'pigeon', 'owl', 'monkey'); 
$testword = array_intersect($result, $keyword); 
print($testword); 


/* Router: Match the ‘Body’ field with index of keywords */ 
switch ($testword) { 
    case 'monkey': 
     monkey(); 
     break; 
    case 'dog': 
     dog(); 
     break; 
    case 'pigeon': 
     pigeon(); 
     break; 
    case 'owl': 
     owl(); 
     break; 

/* Optional: Add new routing logic above this line. */ 
    default: 
    index(); 
} 

ответ

0

array_intersect возвращает массив, то кажется, что вы принимаете «testword» в виде строки. Возможно, вы можете попробовать in_array, чтобы проверить, какое именно ключевое слово точно соответствует

+0

Итак, используя функцию 'in_array', как бы я сделал следующее? PHP-приложение должно проверять наличие совы, голубей, обезьян, собака "в таких строках, как« что стоит эта собака? » или «Что вы можете сказать мне о обезьяне в этой клетке?», и если найдено совпадение с ключевым словом, запустите функцию, основанную на ключевом слове. – Sam

Смежные вопросы