在php中从特定关键字或位置向后遍历
我想从中找到字符串在php中从特定关键字或位置向后遍历,php,Php,我想从中找到字符串 $str = "Hello this is dummy.test. in this string any character, any special character can appear. it is not a fixed type text and predefined. this string will not read manually check by the Programmer.Sorry for the bad English."; 我的算法是
$str = "Hello this is dummy.test. in this string
any character, any special character can appear. it is not a fixed type
text and predefined. this string will not read manually check by the
Programmer.Sorry for the bad English.";
我的算法是固定的,因为某种问题。
首先我想找到测试关键字的位置,然后想从测试返回到虚拟关键字以找到虚拟关键字的位置
我还搜索并使用了internet,但在PHP中没有找到任何可以以这种方式遍历的函数
我还测试了strrpos()
,但没有相关和要求的结果。
有什么解决办法吗
需要输出:虚拟。测试
算法:先右查找(测试),然后从右向左查找(虚拟)。不是先向右(测试),然后从开始向左(虚拟)。
strrpos
才是正确的方法。如果我理解正确,使用offset参数应该可以:
$test = strrpos($str, 'test');
$dummy = strrpos($str, 'dummy', $test);
这将找到在最后一次“测试”之前出现的最后一个“虚拟”。首先使用找到
test
的位置,用剪切字符串直到test
,然后再次使用在子字符串中找到dummy
的位置:
$substring = substr($str, 0, strpos($str, 'test'));
$dummy = strpos($substring, 'dummy');
echo $dummy;
输出:
14
dummy.test.
更新 根据问题编辑,以下函数应该执行您想要的操作。这可能不是最好的解决方案,而且有点难看,但这应该让您开始:
function searchstr($str)
{
$pos = strpos($str, 'test') + strlen($str);
$substring = substr($str, 0, $pos);
$dummypos = strpos($substring, 'dummy', TRUE);
$words = explode(' ', $str);
$chars = -1;
foreach($words as $word)
{
$chars += strlen($word);
if($chars >= $dummypos)
{
return $word;
}
}
return '';
}
echo searchStr($str);
输出:
14
dummy.test.
让我更清楚地更新问题。使用strops()查找“test”的位置;然后在子字符串中为“dummy”指定substring()和strops(),抱歉,我的解决方案不太接近。为什么您得到$substring,然后从开始再次搜索dummy。如果假人试验在10000位置,则??你的代码占用了太多的空间和时间。两者都应该减少。@JohnHarper:你在问题中没有说明这一点。您正在尝试从字符串的右侧进行搜索吗?我只想从右(测试)到左(虚拟)进行搜索。不是从右然后从开始到左。@JohnHarper:预期的输出是什么?需要的输出:dummy.test请看我的问题是否已更新