【发布时间】:2017-03-30 03:29:27
【问题描述】:
我目前正在开发一个使用特定字符串来调用函数的网络应用程序。这是一个示例字符串:
$string = "translate from-to word for translate"
首先我需要验证字符串,它应该像上面的$string。我应该如何验证字符串?
然后我需要从$string中提取3个子串。
- 连字符前面的单词。 (待命名:
$target) - 连字符后面的单词。 (待命名:
$source) -
$source之后到字符串末尾的文本(不包括第一个空格)。 (待命名:$translate)
这是我获取from 和to 的编码尝试:
$found = false;
$source ="";
$target = "";
$next = 3;
$prev = 1;
for($i=0;$i<strlen($string);$i++){
if($found== false){
if($string[$i] == "-"){
$found = true;
while($string[$i+$prev] != " "){
$target .= $string[$i+$prev];
$prev +=1;
}
/*$next -=1;
while($string[$i-$next] != " " && $next > 0){
$source .= $string[$i-$next];
$next -=1;
}*/
}
}
}
从该代码中,我只能在- 之后返回包含to 的$target。
我不知道如何获得$source。
请告诉我获取from 为$source 和to 为$target 的最快方法。
那我需要得到word for translate(from-to之后的所有字符串)。
所以结果应该是
$target = "to";
$source = "from";
$translate = "word for translate";
最后,如果$string有两个连字符,比如translate from-to from-to test-test word for translate,应该是return false;
注意 to 和 from 是随机字符串。
【问题讨论】:
标签: php string delimiter substring