将此伪代码翻译成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 (the sentence) starts with any of the $start
and/or ends with any of the end
separate to get "is of red"
*/
}
与代码本身不仅我会遇到的问题,我也不知道如何进行搜索,如果任何数组值开始于(不仅包含)所提供的$ q。
任何输入都会有帮助。 谢谢
答
像这样的东西应该工作
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);
将返回
是最好的
答
使用strpos
和strrpos
。如果它们返回0,则字符串位于开始/结束处。
不是说你必须使用=== 0
(或!== 0
的倒数)来测试,因为他们返回false
如果字符串没有被发现和0 == false
但0 !== false
。
+0
嗨,那么开始代码怎么样?我想'foreach($ start as $ testvalue){if(strpos($ q,$ testvalue)=== 0){...}}'。我想这会照顾开始的术语,但是如何将这个foreach循环的最后一个术语的测试合并到一起呢? – Kartik 2011-04-15 23:51:43
这种作业的气味。它应该被标记,如果是这样的话...... – Endophage 2011-04-16 00:14:21
@Endophahge不会。我真的很想知道如何翻译。 @ Wh1T3h4Ck5谢谢!会做! – Kartik 2011-04-16 04:24:59