我正在尝试编写一个函数,它基本上是从一个句子中获取一个“属性”。这些是参数。
$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');这就是我想要实现的函数:
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"
*/
}不仅代码本身有问题,我也不确定如何搜索是否有任何数组值以所提供的$q开头(而不仅仅是包含)。
任何输入都会很有帮助。谢谢
发布于 2011-04-16 08:09:52
像这样的东西应该是可行的
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;
}所以在你的例子中,这段代码
$q = "this orange is of orange color";
echo prop($q, $start, $end);打印
是橙色的
这段代码
$q = "this apple is of red color";
echo prop($q, $start, $end);打印
是红色的
这段代码
$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);将会返回
是最好的
发布于 2011-04-16 07:47:04
使用strpos和strrpos。如果它们返回0,则字符串位于最开始/最末尾。
并不是说您必须使用=== 0 (或!== 0进行反向)来测试,因为如果没有找到字符串,它们将返回false,如果没有找到字符串,则返回0 == false,而返回0 !== false。
https://stackoverflow.com/questions/5683371
复制相似问题