I am trying to code a function that basically gets a "property" from a sentence. These are the parameters.
$q = "this apple is of red color"; OR $q = "this orange is of orange color";
$start = array('this apple', 'this orange');
$end = array('color', 'color');
and this is the function I am trying to make:
function prop($q, $start, $end)
{
/*
if $q (the sentence) starts with any of the $start
and/or ends with any of the end
separate to get "is of red"
*/
}
not only am I having problems with the code itself, I am also not sure how to search that if any of the array values start with (not just contains) the $q provided.
Any input would be helpful. Th开发者_如何学Canks
Something like this should work
function prop($q, $start, $end) {
foreach ($start as $id=>$keyword) {
$res = false;
if ((strpos($q, $keyword) === 0) && (strrpos($q, $end[$id]) === strlen($q) - strlen($end[$id]))) {
$res = trim(str_replace($end[$id], '', str_replace($keyword, '', $q)));
break;
}
}
return $res;
}
So in your case this code
$q = "this orange is of orange color";
echo prop($q, $start, $end);
prints
is of orange
and this code
$q = "this apple is of red color";
echo prop($q, $start, $end);
prints
is of red
This code
$start = array('this apple', 'this orange', 'my dog');
$end = array('color', 'color', 'dog');
$q = "my dog is the best dog";
echo prop($q, $start, $end);
will return
is the best
Use strpos
and strrpos
. If they return 0 the string is at the very beginning/end.
Not that you have to use === 0
(or !== 0
for the inverse) to test since they return false
if the string was not found and 0 == false
but 0 !== false
.
精彩评论