将此伪代码转换为PHP
我试图编写一个函数,它基本上从一个句子中获取一个“属性”。这些是参数将此伪代码转换为PHP,php,Php,我试图编写一个函数,它基本上从一个句子中获取一个“属性”。这些是参数 $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 = "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开头(而不仅仅是包含该值)
任何意见都会有帮助。
谢谢使用
strpos
和strrpos
。如果返回0,则字符串位于最开始/结束处
这并不是说您必须使用
==0
(或!==0
进行反向)进行测试,因为如果未找到字符串,它们将返回false
,并且0==false
但是0!==false
类似的方法应该可以工作
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);
印刷品
它是橘色的
这个密码呢
$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);
会回来的
这是最好的
嗨,那么启动代码怎么样?我正在尝试
foreach($testvalue开头){if(strpos($q,$testvalue)==0){…}
。我想这会照顾到开始的学期,但是我如何把上学期的考试和这个foreach循环结合起来呢?这有家庭作业的味道。如果是这样的话,它应该被贴上这样的标签…@enophahge不,它不是。我真的很想知道如何翻译@谢谢!行!