Newbie stuck trying to compare arrays and run a function

Hi guys, I am trying to create an sms auto responder for my business based on the Twilio responder :
[php]<?php

/* Include twilio-php, the official Twilio PHP Helper Library,

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();
}[/php]

I can get this to work just fine, but I’d like it to be able to pick keywords out of a sentence and respond, instead of needing to process single words at a time. Obviously, I will be changing the keywords and the appropriate responses, but I just want to get it working first.

As of right now, if you text any one of those words (owl, monkey, dog, pigeon) by itself it will respond accordingly. If you send one of those words in a sentence (“How much does that pigeon weigh?” for example), it will just respond with the default index. I’d like to be able to set an array of words, have the app check an incoming text against the array of words and if any keyword is in the sentence, it will activate the appropriate response just like it would for a single word. I’ve done a ton of reading on this, and think I may have narrowed down to ‘in_array’ being the best option, but cannot seem to get it to work. I admit that I’m a total newbie to this, and am trying to teach myself code as I go in order to solve my own problem. Can anyone help me make this work? Thanks, and feel free to ask any questions if you need clarification.

  1. You should never echo from a function, it should always return, IMO.
  2. Line 55 doesn’t do what you are describing it to do. Neither should you be removing anything but punc. Otherwise you would break words.
  3. To get all letters to lowercase.
    [php]$result = strtolower($result);
    [/php]
  4. To do this with in array, you would need to get the sentence into an array.
    [php]
    $arr = explode(’ ',$result);
    [/php]
  5. Then check it against the array.
    [php]
    foreach($arr as $word) {
    if(in_array($word,array(‘dog’,‘monkey’,‘etc…’)) {
    $word();
    break;
    }
    }
    [/php]

Thanks! I got it to read with this:
[php]/* 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);
$text = explode(’ ',$result);
$keyword = array(‘dog’,‘pigeon’);
$word = array_intersect($keyword,$text);

$word0;
[/php]

Unfortunately, it only activates whatever word I point to by position, [php][0][/php] in this case. It will read pigeon if I change it to [php] $word[1][/php]. Just using $word doesn’t seem to produce the right result. Any suggestions?

I would go with regular expressions, but that creates other issues for you.

[php]<?php

$str = ‘I am interested in taking look at a listing for 2025 Main Street Blvd, Pleasent Ville.’;

$term = [‘listing’, ‘sale’, ‘open house’];

foreach( $term as $keyword ){

if( preg_match("/{$keyword}/i", $str) ){
    echo respond( $keyword );
}

}

function respond( $word ){

switch( $word )
{
    case 'listing':
        return "I would be happy to show you that listing. I would like to talk to you about your interest. When are you available?";
        break;
    case 'interest':
        return "Let me get more information for you and let you know. Is this the best number to reach you?";
        break;
    case 'open house':
        return "We have open houses going on all the time! Can you give me more information for what you are looking for?";
}

}
[/php]

The biggest problem is the machine learning involved to respond most appropriately.

Thanks, but I don’t think I need any machine learning. All I need to do is pick a keyword out of a text string (have it doing this now) and using it to activate a function of the same name. What I’m stuck on is that I also need the position for the keyword from the keyword array to be dynamic as well, and can’t get it to work. If I change it manually it works as it should. I just want the keyword position to be generated as well. Especially since it needs to be automatic, and I plan to have a lot of keywords. Hope that makes sense.

How do you want to pick the keyword, smartly? or just pick one at random?

Random is easy.
[php]shuffle($keyword);[/php]

Smartly, could use a lot of different approaches.

It has to be the keyword that matches what they wrote. Let’s say my array of keywords is array(‘dog’,‘monkey’,‘owl’,‘pigeon’) and the lead texts in “How much is that pigeon?”. It doesn’t do me any good to send a response about a dog in that case, so I need the matched keyword to send the response most appropriate to what they are looking for.

While calling a dynamic function sounds like a good idea, it doesn’t work for you in the long run.

Wasn’t sure what else to call it, since I know maybe 1% of the terms :confused:
Now what I’m stuck at is that when I try to run the output to ‘$word()’ to run the function it doesn’t work. If I add in the array position of the word in the string like this example:
“How much is the black dog in the cage?” (dog is the keyword here)

$word5;

It will work correctly. The problem is that I need the array position to be automatically populated since I can’t input it manually every time. How can I either do this differently, or have the array position auto-populate?

[php]$index = array_search($keyword, $term);
echo "

{$keyword[$index]} was called

";
[/php]

array_search will find the index of the array value, when found.

But I am telling you as plainly as possible, you do not want to use a dynamic variable/ function name. You either want to structure you approach, or use anonymous functions ( if you version of php allows for it).

You could create classes: a class for each keyword. One of the properties could be a return value text string.

Oh, I appreciate it, and sorry if I seem so dense. I’m just really new to all this, and only learning to code to create a solution for myself that no one has created yet.

Anyway, I had tried (sort of) to use the array search, but it didn’t seem to work unless I specified a single word to look for. The format you provided there, didn’t function correctly. I need a keyword to be pulled out of a string of text and then a response/ function sent based on that keyword. I’ll see if I can’t fudge with it a bit more, and I think I’m struggling a bit to explain what I want or need to happen.

Clearly defined goals would help. I have created similar, but mine is used for email systems. The same thing, just different protocol to get the search string.

I was attempting to modify the working version, to what you were currently using, without success. The first argument is the array value you are looking for, the second is the array you are looking in.

Here is the code I have now:
[php]<?php

/* Include twilio-php, the official Twilio PHP Helper Library,

include(‘Services/Twilio.php’);

/* 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);
$text = explode(’ ',$result);
$keyword = array(‘dog’,‘pigeon’,'owl,‘monkey’);
$word = array_intersect($text,$keyword);

$word[?];
/* ^^^This is the issue. */

/* 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;
}[/php]

Here’s what I started with:
[php]<?php

/* Include twilio-php, the official Twilio PHP Helper Library,

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();
}[/php]

And here is what I am trying to do (thanks for all the help and patience):

I have advertising for my real estate business and receive leads from web portals like Realtor.com and Zillow/ Trulia. When I receive a lead I have the contact information parsed and a lead created in my CRM. When this happens, I have an automatic response that sends out an email and a text to the contact info that is provided.

When someone replies to the email, the CRM or I handle it. When someone responds to the text message, the CRM would do nothing. So, I’m trying to get Twilio to handle the auto reply side of things.

What I want to happen is that after the initial text goes out, if a lead replies to the message any keywords that they send will be read by my custom Twilio app and the app will respond in kind to specific keywords. Right now, I am building it with the boilerplate keywords and responses you see, but will change those out once this is working correctly.

The stock auto-responder from Twilio only works if single keywords are sent to the sms app. I know that based on how it’s implemented and applied, that won’t happen. So, I need the app to be able to read a text message sentence, pick out keywords, and respond based on those.

For example: A lead gets the auto response and says - “What is the age of the roof?”. The app strips away the rest of the words and sees that the sentence contains a keyword - ‘roof’. It would then send the response (function) for ‘roof’.

I have it working correctly with the small exception that right now, the function also needs the array position of the keyword in the incoming text string. For the above example, while I’d want it to work if the output $word(); matched the ‘roof();’ function, it requires that it have $word?;, or in this case roof6; in order to work. Problem is I can’t get the array position to appear automatically with the correct number. I either need to find a way to do that, or another way to swap in the correct function.

TL;DR:

[ul][li]Text string of inconsistent length comes in containing keyword.
App ‘reads’ sentence and extracts keyword based on the array of words I have set.
The word is confirmed to be a keyword and is then output to the functions in order to send the response that corresponds to the keyword.[/li]
[li][/li][/ul]

Here is a working example to try out:

[php]function b(){
echo “

Test b

”;
}

function a(){
echo “

Test a

”;
}

$str = ‘This is a test’;
// first part is the string to search for. The second is the method name to call when found.
$terms = [
‘test’ => ‘a’,
‘string’ => ‘b’
];

$t = explode(’ ', $str);

foreach( $t as $v ){
if ( array_key_exists($v, $terms) ){
echo “Received $v, calling {$terms[$v]}()”;
$terms$v;
}
}[/php]

Thanks, I’ll give that a shot in a bit. So that will activate functions like I’m looking to do?

This allows you to map array keys to user defined functions. Whatever you define in the function portion of the array is called when that string value is found.

I think I’ve got an idea how this is supposed to work, but not the correct implementation. Here’s the code you gave me in the code I’m working with:
[ph]/* 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);
$text = explode(’ ',$result);
$keyword = [
‘dog’ => ‘a’,
‘pigeon’ => ‘b’,
‘owl’ => ‘c’,
‘monkey’ => ‘d’

];
$word = array_intersect($text,$keyword);

foreach( $word as $v ){
if ( array_key_exists($v, $keyword) ){
$word$v;
}[/php]

Can you tell me what I’m doing incorrectly here?

Hey, astonecipher, I solved the problem, and got it to work exactly the way I wanted to. I wanted to thank you for spending a lot of time on this, though in the end your solution didn’t work. I ended up just thinking through it and it’s exactly what I need. I seriously appreciate your time on this though. If you’re ever in NH hit me up, I owe you a beer.

Glad to hear it is solved.

I pm’d you the solution because you put in some time on this, but I don’t want the answer on the net because I fought with it way too much to give it away for free :confused:

Sponsor our Newsletter | Privacy Policy | Terms of Service